Posted By

garside on 12/10/08


Tagged

javascript include script jquery backloading includer automatic


Versions (?)


Advertising

Website Promotion DIRECTORY is a crucial factor for all websites that need to gain better organic search engine rankings and increase website traffic.
Submitting your website as part of your Web Promotion strategy to our SEO friendly and high traffic Business Directory for review is an excellent way to gain a valuable backlink and increase your websites visibility online.

Submit Site


Who likes this?

5 people have marked this snippet as a favorite

xuanyan
jamesming
bryandease
umang_nine
vali29


jQuery Automatic Script Includer


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
  1. // Add this onDocumentReady function to the end of the jQuery.js file.
  2. // It MUST be in the jquery file to work correctly.
  3. $(function(){
  4. var scripts = /\?(.*)/, files = [], path = /^.*\//, loaded = 0, count = 0;
  5.  
  6. $('script').each(function(){
  7. var src = $(this).attr('src');
  8. if (!scripts.test(src)) return;
  9. var pathto = src.match(path);
  10. files = files.concat($.map(src.match(scripts).pop().split(','), function(e,i){
  11. return pathto+e+'.js'
  12. }));
  13. })
  14.  
  15. count = files.length;
  16.  
  17. $.each(files, function(){
  18. $.getScript(this, function(){
  19. loaded++;
  20. if(loaded == count && typeof onBackload == 'function')
  21. onBackload(loaded)
  22. })
  23. })
  24. });
  25.  
  26. /**
  27.  * If you have the following script tags:
  28.  * <script src="/path/to/jquery.min.js?somefile,otherfile.min,thirdfile"></script>
  29.  * <script src="/other/path/foo.js?different.file,final.file"></script>
  30.  * This script will "backload" the following files:
  31.  * /path/to/somefile.js
  32.  * /path/to/otherfile.min.js
  33.  * /path/to/thirdfile.js
  34.  * /other/path/different.file.js
  35.  * /other/path/final.file.js
  36.  */
  37.  
  38. // And if you declare a function named "onBackload", it will be fired when all the scripts are loaded
  39. // This is handy for getting things going once you're confident your scripts have all been included.
  40. function onBackload(loaded){
  41. alert('All ' + loaded + ' files backloaded!')
  42. }

Report this snippet 

You need to login to post a comment.

Download royalty free graphics