5

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.

2
  • Try to rephrase your question, I don't undestand what you're asking... Commented Nov 26, 2011 at 12:48
  • You should add the list of methods/functions that you found. Commented Nov 26, 2011 at 12:54

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

jQuery is not a good solution. need pure javascript based solution.
5

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);
}

1 Comment

I said I dont need callback function, altohugh I can remove the part that relate to the callback. why do you add it to the head tag and not to the body, does it really matter? + Shouldnt I remove the element as soon as it loaded?
3

Something like

function getScript(url) {
    e = document.createElement('script');
    e.src = url;
    document.body.appendChild(e);
}
getScript('jstoload.js');

this?

1 Comment

Is it corss browser solution?, should I remove the element once its loaded?
0

The YUI Loader sounds like a good choice for you. It will also allow you to add your own custom modules, so you can load on demand, as well as load all other JS files that are required as well.

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.