7

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);
2
  • 3
    Using a custom event like that is a fine idea. Commented Mar 29, 2016 at 14:31
  • 1
    Assuming "without using any external library" includes jQuery, it's worth considering that your homebrew event, while effective, will require you to handle the case wherein the script can't be loaded. I think what you're looking for is a 'promise'. Commented Mar 29, 2016 at 14:46

4 Answers 4

10

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
Sign up to request clarification or add additional context in comments.

Comments

8

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

Comments

0

Here is a function that would be help to load a script and on successful load.. you can wait and perform your actions

function loadScript(url) {
  const w = window;
  const d = document;
  const l = () => {
    const s = d.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = url;
    const x = d.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);

    s.addEventListener('load', () => {
      // This loads the script
      yourFunctionAfterScriptLoaded();
    });
  };
  if (w.attachEvent) {
    w.attachEvent('onload', l);
  } else {
    w.addEventListener('load', l, false);
  }
}

or you can directly use the script onload function as shown in this link

Comments

-2

you could read the file source and inserting it in a script tag manually, so you will have the AJAX response event

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.