简体   繁体   中英

jQuery: Lazy Loading for JS

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

  1. Can anyone recommend a good plugin for this?
  2. Any "real world" advice implementing such a strategy? Any "gotchas" I should look out for?

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

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

This will ensure that you never load more javascript than you need to. If the user never clicks on the element, you never loaded the javascript for the event. There will be a small delay for the HTTP request, so you should probably indicate a loading animation on click while the script loads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM