Home > Web Front-end > JS Tutorial > How to dynamically load js script files using jQuery_jquery

How to dynamically load js script files using jQuery_jquery

WBOY
Release: 2016-05-16 16:53:32
Original
1141 people have browsed it

They are powerful, but sometimes the gain outweighs the gain. If you are using jQuery, there is a built-in method for loading 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 completed, you can perform subsequent operations in the callback function. The most basic way to use jQuery.getScript is as follows:

Copy the code The code is as follows:

jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) {

/*
Do some things that need to be executed after loading is completed
*/

});


This getScript method returns a jqxhr, you can use it like this:
Copy code The code is as follows:

jQuery.getScript("/path/to/myscript.js")
.done(function() {
/* Yeah, No problem, what can be done here*/
})
.fail(function() {
/* Damn, perform the rescue operation immediately*/
});

The most common use of jQuery.getScript is to lazy load a js plugin and execute it when loading is complete:

Copy code The code is as follows:

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

2. Caching problem

There is a very important issue. 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:

Copy code The code is as follows:

jQuery.ajaxSetup({
cache: true
});

Copy code The code is as follows:

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

Be careful about caching issues when loading scripts!
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