Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - function to load external JS files is needed

Tags:

javascript

Recently I added to my website facebook like button, twitter follow us button and google +1 button. I want their JS scripts to load when I tell them to load.

Therefore, I need a function that load external JS files. I don't need to know when the file finished to load (callback is not needed).

I found some methods/functions on the Internet, but I want to know which would be the best choice for this situation?

4 ways to dynamically load external JavaScript
Dynamically loading JS libraries and detecting when they're loaded
The best way to load external JavaScript

Thanks.

Edit: Added the methods/function I found.

like image 785
Ron Avatar asked Nov 26 '11 12:11

Ron


2 Answers

I would recommend using jQuery's getScript(). For the twitter-button, you would load the corresponding script like that:

$.getScript("//platform.twitter.com/widgets.js")

Of course you would have to load jquery in your script first and do not forget to add the markup needed for the twitter-button in your html.

like image 186
florianletsch Avatar answered Nov 02 '22 23:11

florianletsch


This might be helpful:

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;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}
like image 36
Sudhir Bastakoti Avatar answered Nov 02 '22 23:11

Sudhir Bastakoti