ThomasReggi
ThomasReggi

Reputation: 59585

Event for when file has loaded

The code below runs on a page:

(function() {
  function asyncLoad() {
    var urls = ["https://something.com/script.js"];
    for (var i = 0; i < urls.length; i++) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.async = true;
      s.src = urls[i];
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
    }
  }
  window.attachEvent ? window.attachEvent('onload', asyncLoad) : window.addEventListener('load', asyncLoad, false);
})();
//]]>

I need an event listener that fires when this file is available in the DOM.

I need to utilize variables from this script.

I need to know when https://something.com/script.js has been loaded and if it is not I would like a backup to fire. This can happen if the file hasn't loaded within a designated period of time.

Alternatively I could use an event for when a variable is available from the script.js file.

Upvotes: 0

Views: 496

Answers (2)

RobG
RobG

Reputation: 147523

Script elements support the load event, so you should set the listener on the script element before inserting it in the DOM, e.g.

  s.src = urls[i];

  s.onload = asyncLoad; // add load listener

  var x = document.getElementsByTagName('script')[0];
  x.parentNode.insertBefore(s, x);     

If you want to know if it arrived successfuly or not, use XMLHttpRequest to get the content, then assign it to the script element's text property. That way you can know if the script was retreived, set a timeout in case of failure and take corrective action and not lock the browser in the meantime.

Upvotes: 1

Nhu Trinh
Nhu Trinh

Reputation: 13986

If in your script.js has a function for example: function a() then you can catch when it available like this

var checkScript = function(){
   if (typeof a  === "function"){
      //fire event
   }else{
      setTimeout(checkScript, 1000);
   }
}
checkScript ();

Upvotes: 1

Related Questions