5

I have the following function:

function require(url)
{
    var e = document.createElement("script");
    e.src = url;
    e.type="text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e);
}

Which allows to dynamically load javascript at runtime, and I need to add a callback after loading some new files

For example when I

require('className.js');

and just after this call

var a = new window[className];

file has not been loaded yet, so it generates an error.

1
  • 2
    require(url, callback) { ... e.onload = callback } Commented Sep 6, 2014 at 14:07

2 Answers 2

17

You can add an onLoad on the script element, but beware that on some older version of IE is a bit buggy.

Taking your code as a reference :

function require(url, callback) 
{
  var e = document.createElement("script");
  e.src = url;
  e.type="text/javascript";
  e.addEventListener('load', callback);
  document.getElementsByTagName("head")[0].appendChild(e);
}

require("some.js", function() { 
   // Do this and that
});
Sign up to request clarification or add additional context in comments.

2 Comments

You are almost right... but e.addEventListener('load', callback); is better)
Edited with addEventListener
2

Further to Simone Gianni 's answer, in case you want to load a set of js files, plus run a callback at the end, where you want to ensure all files have loaded, you can do it recursively as follows:

function loadList(list, i, callback)
        {
            require(list[i], function()
            {
                if(i < list.length-1)
                {
                    loadList(list, i+1, callback);  
                }
                else
                {
                    callback();
                }
            });
        }

Call with:

    loadList(jsList, 0, function()
    {
        // code that applies after all URLs in jsList have loaded
    });

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.