Gurnzbot
Gurnzbot

Reputation: 4132

How to poll a module loaded dynamically in Javascript

I have a module that I load in the following way in Javascript once a page is scrolled to a certain point:

newScript = document.createElement('script');
newScript.setAttribute('src','scripts/GalleryLoader-min.js');
document.body.appendChild(newScript);

This works well, but I'd like to call an init() function once loaded. The following works but seems like something I should be able to put into it's own function and reuse:

var currentChance = 500;
var refreshIntervalId = setInterval(function(){
    currentChance--;

    console.log("Waited");
    if (typeof NS.GalleryLoader !== 'undefined') {
        console.log("Loaded: "+NS.GalleryLoader);
        NS.GalleryLoader.init();
        clearInterval(refreshIntervalId);
    }
    else if (currentChance > 0) {
        console.log("Trying again: "+NS.GalleryLoader);
    }
    else {
        console.log("Unable to Load "+NS.GalleryLoader);
        clearInterval(refreshIntervalId);
    }   
}, 10);

When I attempt to put that into a function the module is always "undefined" and never ends up telling me it's loaded. Pretty sure I'm not passing the namespace/module name currectly in order to check it.

Upvotes: 1

Views: 59

Answers (2)

Eugene Tiurin
Eugene Tiurin

Reputation: 4129

You may want to use the element load event

newScript.onload=function(){
//YOUR CODE HERE
}

Upvotes: 0

Buzinas
Buzinas

Reputation: 11725

You can use the onload event of the HTMLScriptElement.

newScript.addEventListener('load', funcion() {
  NS.GalleryLoader.init();
});

You can even create a generic function like this:

function loadScript(path, callback) {
  var s = document.createElement('script');
  if (callback)
    s.addEventListener('load', callback);
  s.async = true;
  s.src = path;
  document.querySelector('head').appendChild(s);
}

And then use it:

loadScript('scripts/GalleryLoader-min.js', function() {
  NS.GalleryLoader.init();
});

Upvotes: 2

Related Questions