I need to get some script from the different social networking site, and I want to cache them. Not 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 id much faster. I do not know why, but it just is. Here is the code.
// 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.
Anyone have any suggestions if this is actually a good way of doing this. Maybe some adjustments to the code, or go a complete other way with this. Every suggestion is welcome.
Edit
After a little bit of research and looking at the hint Arthur P gave me I changed the script to just native javascript:
var shareUrls = [
'//platform.twitter.com/widgets.js',
'http://static.ak.fbcdn.net/connect.php/js/FB.Share',
'https://apis.google.com/js/plusone.js',
'http://platform.linkedin.com/in.js'
];
if( shareUrls.length > 0 ){
for(var i=0; i<shareUrls.length;){
var e = document.createElement('script');
e.src = shareUrls.shift();
e.async = true;
document.getElementsByTagName('head')[0].appendChild(e);
}
}
The trick is here to set e.async = true;
this forces the scripts to be downloaded asynchronous. Otherwise they will be loaded one at a time.
Now Arthur P suggestion using another library such as YUI or jsload would be overkill IMO. But using using normal <script>
tags as he suggested was a good tip.