Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Autoloader?

Is there a solution out there where I can have JavaScript/jQuery autoload dependent files when needed? For example, consider this scenario:

  1. I have an autoloader script listening for when a particular script needs to be loaded.
  2. A jQuery dialog() plugin is called.
  3. The autoloader is told to listen for when this plugin is called, and loads the jQuery UI.
  4. If more dialogs are called in the future, the required script will not be loaded.

Is this too much effort for simply trying to limit bandwidth? Should I just include all of the core files in one superpackage and be done with it?

Thank you for your time.

like image 511
Oliver Spryn Avatar asked Jun 21 '11 20:06

Oliver Spryn


2 Answers

Yes you should inclde all of the scripts in one file. Or at least most of them groupped like this: jquery.js, global.js (that's where frequently - on more than one, two pages - used scripts should be) and page_specyfic.js. Imagine that a dialog() is called and the user has to wait for .js to download and plugins to initialise. Savings in bandwith (if any) wouldn't be worth harming the users expirience.

like image 190
Litek Avatar answered Nov 14 '22 03:11

Litek


There are many examples of on demand script loading out there. For example remy sharp has a code sample on his blog that you could either use as is or turn into a jQuery plugin. Unfortunately it may not work in all browsers.

There is also the jQuery Lazy Plugin Loader which loads jQuery plugins on demand rather than up-front. To use it you would need to set up lazy loading for each piece of jQuery UI you are using as follows (name will be the function name for each piece you use):

$.lazy([{
   src: 'jquery-ui-1.8.14.custom.min.js',
   name: 'dialog'
}]);

You can also use the techniques in this question about loading jQuery itself on demand. For example you can dynamically create a script tag at the time needed to load jQuery UI.

Finally since you are talking about jQuery UI consider getting it from Google's CDN, which is likely cached in the user's browser anyway.

like image 3
justkt Avatar answered Nov 14 '22 02:11

justkt