Loading JavaScript files dynamicly and waiting async for it

Have you ever been trying to load JavaScript dynamicly?
That is a cool way to reduce the initial loading time, but there are way more usecases for it.

The question is: how to do it?
The most important thing in JavaScript development is that you need to keep an eye on the performance. And loading some files can cost a lot of performance. So how should you do it?
The answer is that you need to load the script asynchronously. After loading it you can fire your function you need.
I wrote a litle function that does the work for us. All you need to do is to add this function into your code and call it with the url of your scriptfile and a callback function that should be fired after the script is loaded.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function loadScript(url, callback) {
    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) {  //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" ||
                    script.readyState == "complete") {
                script.onreadystatechange = null;
                // execute callback after script loaded
                callback();
            }
        };
    } else {  //Others
        script.onload = function () {
            // execute callback after script loaded
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

And here is how to use it:

1
2
3
4
5
6
function getScriptXY () {
    loadScript("http://yoururl.com/scriptfolder/filename.js", function () {
       //do whatever you want e.g. call a function that is in your dynamicly loaded script
       functionInScript();
    });
}

Comments

Popular posts from this blog

How to support multiple languages in WPF