Home > Web Front-end > JS Tutorial > body text

Detailed explanation of jQuery getScript() method loading JavaScript and handling caching issues

伊谢尔伦
Release: 2017-07-21 15:51:21
Original
3024 people have browsed it

Dynamic loading of Javascript is a very powerful and useful technology. If you are using jQuery, it has a built-in method that can be used to load a single js file. You can use this method when you need to delay loading some js plug-ins or other types of files. Here’s how to use it!

1. The jQuery getScript() method loads JavaScript

jQuery has a built-in method to load a single js file; when the loading is complete, you can call it in Perform subsequent operations in the function. The most basic way to use jQuery.getScript is this:

jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {
 /*   做一些加载完成后需要执行的事情 */ 
});
Copy after login

This getScript method returns a jqxhr, you can use it like the following:

jQuery.getScript("/path/to/myscript.js")
 .done(function() {
  /* 耶,没有问题,这里可以干点什么 */
 })
 .fail(function() {
  /* 靠,马上执行挽救操作 */
});
Copy after login

The most common place to use jQuery.getScript It is to delay loading a js plug-in and execute it when the loading is completed:

jQuery.getScript("jquery.cookie.js")
 .done(function() {
  jQuery.cookie("cookie_name", "value", { expires: 7 });
});
Copy after login

2. Caching problem

There is a very important problem when using jQuery.getScript , you need to use a timestamp string following the js address that needs to be loaded to prevent it from being cached. However, if you want this script to be cached, you need to set the global cache variable, like this:

jQuery.ajaxSetup({
  cache: true
});
Copy after login
jQuery.ajax({
      url: "jquery.cookie.js",
      dataType: "script",
      cache: true
}).done(function() {
  jQuery.cookie("cookie_name", "value", { expires: 7 });
});
Copy after login

Be sure to be careful about caching issues when loading scripts!

The above is the detailed content of Detailed explanation of jQuery getScript() method loading JavaScript and handling caching issues. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template