Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did wrapping my JavaScript library in an anonymous function fix my race condition?

Question: Why did wrapping my JavaScript library in an anonymous function fix my race condition?

Note: I am also interested in commentary on good solutions for synchronously and asynchronously loading external JavaScript resources.

I am working on a project that involves writing a browser extension using crossrider. If you are not familiar with cross rider extensions they are implemented in JavaScript, you have a background page that can communicate with an app page. The app page can runs with each open tab and can manipulate the DOM. I plan to load most of the extension code remotely when the user requests it to open. Recently I ran in to a race condition when I added a script tag to the page referencing Raphael, and then something I built out of graffle

From what I understand if a page is loaded with those script tags already in place, then the execution will take place synchronously, although since I was appending the script tags the execution took place asynchronously. This is the opposite problem that most people seem to have. Messing around with it I learned that wrapping my code graffle code in an anonymous function fixed my race condition. Why? I read this post on wrapping whole Javascript files in anonymous functions, and that doesn't seem to having anything to do with race conditions.

My calling code:

var scriptsToLoad   = [ "http://example/Scripts/lib/raphael.js",
                "http://example/Scripts/lib/graffle.js",
                "http://example/Scripts/lib/log4javascript.js"];

for(var i in scriptsToLoad) {
    (function(){
        $("head")
            .append($("<script></script>")
                .attr("type", "text/javascript")
                .attr("src", scriptsToLoad[i]));
    })()
}
like image 365
TMB Avatar asked Nov 05 '22 13:11

TMB


1 Answers

Regarding your question, I do not believe that there has been any particular standard set for the order in which <script /> tags are loaded and evaluated; it is easy to introduce race conditions.

Regarding (a)synchronous script loading, with jQuery, do this:

var scriptsToLoad = [
    "http://example/Scripts/lib/raphael.js",
    "http://example/Scripts/lib/graffle.js",
    "http://example/Scripts/lib/log4javascript.js"
];

$.each(scriptsToLoad, function (index, script) {
    $.ajax({
        url      : script,
        async    : false,
        dataType : 'script'
    });
});
like image 134
Dylon Avatar answered Nov 10 '22 18:11

Dylon