/ Published in: jQuery
If you have a lot of javascript you need to load to make your page work, but don't want to load all of it before the user sees your page, you can use this handy script to backload it all.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// Add this onDocumentReady function to the end of the jQuery.js file. // It MUST be in the jquery file to work correctly. $(function(){ var scripts = /\?(.*)/, files = [], path = /^.*\//, loaded = 0, count = 0; $('script').each(function(){ var src = $(this).attr('src'); if (!scripts.test(src)) return; var pathto = src.match(path); files = files.concat($.map(src.match(scripts).pop().split(','), function(e,i){ return pathto+e+'.js' })); }) count = files.length; $.each(files, function(){ $.getScript(this, function(){ loaded++; if(loaded == count && typeof onBackload == 'function') onBackload(loaded) }) }) }); /** * If you have the following script tags: * <script src="/path/to/jquery.min.js?somefile,otherfile.min,thirdfile"></script> * <script src="/other/path/foo.js?different.file,final.file"></script> * This script will "backload" the following files: * /path/to/somefile.js * /path/to/otherfile.min.js * /path/to/thirdfile.js * /other/path/different.file.js * /other/path/final.file.js */ // And if you declare a function named "onBackload", it will be fired when all the scripts are loaded // This is handy for getting things going once you're confident your scripts have all been included. function onBackload(loaded){ alert('All ' + loaded + ' files backloaded!') }