Home  >  Article  >  Web Front-end  >  Detailed explanation of jquery getScript dynamic loading JS method improvement

Detailed explanation of jquery getScript dynamic loading JS method improvement

巴扎黑
巴扎黑Original
2017-07-03 10:09:481406browse

Many friends need to use the getScript method to dynamically load JS. This article will introduce in detail how to implement this function

Copy code

$.getScript(url,callback )

This method is a method provided by jquery itself for dynamically loading js. When a website needs to load a large amount of js, dynamic loading of js is a better method. When a certain function is needed, the corresponding js is loaded.
But I found some unsatisfactory aspects during use.


You will request this js every time you need to execute this function. Isn’t this a disservice?
So I found the API description of Jquery official website http://api.jquery.com/jQuery.getScript/
In fact, this method is an encapsulation of the ajax method, you can use the ajax method caching To change the http status 200 to 304, thereby using the client's cache:

The code is as follows:

$.ajaxSetup({
cache: true
});


So, you will find that every time you call this function, it becomes as follows:


Every time js is called, the following parameters similar to "?_=13126578" are gone, and the status is Not Modified.
But I’m a bit of a germophobe. Every time I use this function, although the server no longer has to return the entire js file, it still has to request the server every time, which always makes me feel uncomfortable. Hence the title of this blog was born.
Without further ado, let’s start with the code:

The code is as follows:

 
 
 
 
 
 
 



The code in t1.js is also a function

The code is as follows:

function alertMe() {
alert('clicked me');
}


At this point, the entire transformation is complete Yes, when you use this function, you will only send a js request to the server during initialization. After the loading is completed, you will not request the server again, even if it is 304status code. There will be.

I am a newbie in js, please give me a pat, O(∩_∩)O~

The above is the detailed content of Detailed explanation of jquery getScript dynamic loading JS method improvement. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn