Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add callback after dynamically loading javascript file

Tags:

javascript

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.

like image 977
Oleg Patrushev Avatar asked Sep 06 '14 14:09

Oleg Patrushev


People also ask

Is it possible to dynamically load external JavaScript files in JavaScript?

Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.

What is callback in JavaScript stack overflow?

A JavaScript callback is a function which is to be executed after another function has finished execution. A more formal definition would be - Any function that is passed as an argument to another function so that it can be executed in that other function is called as a callback function.

How do I load a script file in JavaScript?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.


2 Answers

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
});
like image 135
Simone Gianni Avatar answered Oct 23 '22 22:10

Simone Gianni


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
    });
like image 31
Randhir Rawatlal Avatar answered Oct 23 '22 21:10

Randhir Rawatlal