Help Needed: Can't get basic JavaScript to fire in Canvas (external .js)

Jump to solution
NatFeibish
Community Explorer

Hi, all. 

I have been trying for literal weeks to get JavaScript to fire in Canvas using event listeners -- no taboo HTML tags -- and I can't seem to get it to work. The JS works fabulously on other servers, but something about the way Canvas calls it is throwing an error that the properties haven't loaded. (For those who are Canvas admins, you can see the page here. ) You can see the working code on one of my non-canvas servers here. Really basic stuff.

The Canvas response is: "The issue is the custom theme is loading before your wiki page and by the time the page is loaded the DOMContentLoaded event has already fired so you're always going to get the message
'Element with class "a.helloWorld" not found.' The method you're current trying to implement to trigger JS on your wiki page waiting for the DOMContentLoaded event isn't going to be reliable and I'd suggest investigating other options for finding your elements and setting up your listeners for your page."

The JS fires from the same subaccount as the course. There is no other JS that loads before it in upper subaccounts, and no other apps running anywhere.

I have tried with and without DOMContentLoaded, and I really have no idea how to get a simple event listener working. The JS is really very simple.

How, in Canvas, using the Theme Editor to hold your .js, can you use an event listener?

If you don't want to mess with my code, I'll even take a piece of code using an event listener that you know works in your instance. Something super simple, like with tabs or even an alert.

Labels (1)
0 Likes
1 Solution
JamesSekcienski
Community Coach
Community Coach

Instead of using DOMContentLoaded, you could try checking if the window is loaded.

window.addEventListener("load", () => {
  // Do stuff
});

 You could also set-up a MutationObserver.  This should provide the quickest update once the detected content is loaded, but it is also more complex to set-up.

The Best Practices for Using Global JavaScript InstructureCon 2013 presentation also has an example of an onElementRendered function you could use to continue to check for an element and then do something once it finds it or stops trying after a certain number of attempts>

View solution in original post