Dynamically loading JavaScript synchronously

Posted by spoon16 on Stack Overflow See other posts from Stack Overflow or by spoon16
Published on 2010-05-21T04:10:41Z Indexed on 2010/05/21 4:20 UTC
Read the original article Hit count: 217

Filed under:

I'm using the module pattern, one of the things I want to do is dynamically include an external JavaScript file, execute the file, and then use the functions/variables in the file in the return { } of my module.

I can't figure out how to do this easily. Are there any standard ways of performing a pseudo synchronous external script load?

function myModule() {
    var tag = document.createElement("script");
    tag.type = "text/javascript";
    tag.src = "http://some/script.js";
    document.getElementsByTagName('head')[0].appendChild(tag);

    //something should go here to ensure file is loaded before return is executed

    return {
        external: externalVariable 
    }
}

© Stack Overflow or respective owner

Related posts about JavaScript