HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Loading JavaScript files asynchronously

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptasynchronouslyfilesloading

Problem

I need to get some scripts from the different social networking site and cache them. I want the function to be asynchronous, and non-blocking.

I have settled with a script, but I am not really sure if it is not overly complicated to do the job.

I did replace a normal for loop, and this method is much faster. I do not know why, but it just is.

// Cached scritps
var cachedScriptPromises = {};

// Location of the scripts
var Scripts : {
    twitter    : '//platform.twitter.com/widgets.js',
    facebook   : 'http://static.ak.fbcdn.net/connect.php/js/FB.Share',
    googleplus : 'https://apis.google.com/js/plusone.js',
    linkedin   : 'http://platform.linkedin.com/in.js'
};

// When the button is clicked all the scripts
// are loaded. The conainers are already
// on the website. They will be filled
// as soon as the script is loaded.
jQuery('a.share-link').click(function(){
    for( var script in Scripts ){
        jQuery.cachedGetScript( Scripts[script] );
    }
});

// Function that get and caches the scripts
jQuery.cachedGetScript = function( script ) {
    if ( !cachedScriptPromises[ script ] ) {
        cachedScriptPromises[ script ] = jQuery.Deferred(function( defer ) {
            jQuery.getScript( script ).then( defer.resolve, defer.reject );
        }).promise();
    }
    return cachedScriptPromises[ script ];
};


Eventually this function can be expanded by adding some before and after actions. The thing is that the files are loaded so quickly that I have removed these features, but I am planning to do this as soon as the project becomes bigger.

Does anyone have any suggestions on making this better? Maybe some adjustments to the code, or go a complete other way with this.

Solution

I believe you don't need to use jquery deferred objects for this task. Just use script tags with sources - they will be downloaded in parallel from CDNs (try to use CDN, its always a good idea). The amount of parallel requests will be limited by browser restrictions.

Since your code just replaces default browser technique, for more sophisticated features (like dependent components, libraries that you really want to defer, because they are not used until some action on the page), use

  • http://jsload.net/



  • http://developer.yahoo.com/yui/get/



  • deferred objects as you did

Context

StackExchange Code Review Q#6110, answer score: 3

Revisions (0)

No revisions yet.