Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript how to wait for dynamically injected scripts are loaded before start using them?

Tags:

javascript

Without using any external library how can I wait for a script to load before using it.

In my case I'm loading the scripts using:

(function (w,d,t,s,e,r) {

    e = d.createElement(o);
    r = d.getElementsByTagName(o)[0];
    e.async = 1;
    e.src = g;
    r.parentNode.insertBefore(e, r)

})(window, document, 'script', '//mydomain.com/path/to/script.js');

And later:

// then later I want to use some code form the script:
var obj = new classFromTheInjectedScript();

Is there away to wait for the script to load and then start using it?

Note: I have a way that I can trigger an event within the script I want to load and then listen to it as you can see below, but is this a good idea?

(function(w,d){

    document.addEventListener('scriptLoadedCustomEvent',onScriptReady);

    function onScriptReady(){
        // what I need to do goes here!
    }


})(window,document);
like image 965
Mustafa Dwekat Avatar asked Mar 29 '16 14:03

Mustafa Dwekat


2 Answers

You should be able to do something like this!

    var script = document.createElement('script');
    script.src = url; //source 

    var callback = function (){ 
      // do stuff after loaded
    }
    script.onload = callback;

    document.head.appendChild(script); //inject where you need it to be
like image 193
joe.gonz Avatar answered Oct 12 '22 07:10

joe.gonz


You can use onload and onerror events for <script> tag. Good example here.

like image 31
Mikalai Avatar answered Oct 12 '22 08:10

Mikalai