简体   繁体   中英

Loading jquery once across all pages

Is there a method that allows me to load jQuery only one time across multiple pages? I am loading external pages inside a div.

$("#home").click(function(e) {
   e.preventDefault();$("#content").html(ajax_load).l‌​oad("page.html"); 
});

The pages I am loading require Jquery. Instead of calling jQuery eg: ( <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> ) on each of these external pages can I call the already loaded version or do I have to call Jquery again and again?

I ask this because am I not repeating the constant loading of jquery libary on each external page and does this not slow down the load of the external pages?

If you are loading the external pages via ajax into a page with jquery, then you only need to load jquery on that containing page. So I suppose the answer is yes, you can reference the already loaded version of jquery.

Just be sure to include the selector parameter in any event listeners (such as .on() ) to delegate the event since the content you are adding is dynamically added and not directly bound. http://api.jquery.com/on/#direct-and-delegated-events

If you have jquery loaded in the external pages that are getting ajaxed in, the main page will then have two different jquery libraries loaded, which is not what you want as it can cause all types of issues.

This will load the entire page inside #content . If there are no other scripts needed, eg. others .js files, from the external page you can wrap everything in your body tag in a div and do the following:

$("#content").html(ajax_load).load("page.html#wrapper");

This will load only what is in #wrapper.

I can't remember why, but I know that you can't just use the body tag as a selector for this.

Note: the div does not have to be called wrapper.

Hope this helps!

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