JQuery: Lazy Download for JS

I read http://ajaxpatterns.org/On-Demand_Javascript and was interested in the "lazy loading" of my JS. Questions:

  • Can anyone recommend a good plugin for this?
  • Any β€œreal world” advice that implements such a strategy? Any "gotchas" that I should pay attention to?
+4
source share
1 answer

No plugin needed. You can use jQuery $.getScript() . Just put the specific javascript event in a separate file, then bind the event that calls $.getScript() .

 $(function() { $('#yourElement').click(function() { $.getScript('/path/to/script.js'); }); }); 

This ensures that you never download more javascript than you need. If the user never clicks on an element, you never loaded javascript for the event. There will be a slight delay for the HTTP request, so you should probably specify a loading animation when you click while the script loads.

0
source

All Articles