How to Use jQuery to dynamically load js script files

Source: Internet
Author: User
Tags getscript

They are powerful, but sometimes they will not be worth the candle. If you are using jQuery, there is a built-in method in it that can be used to load a single js file. This method can be used when you need to delay loading some js plug-ins or other types of files. The following describes how to use it!

I. jQuery getScript () method loading JavaScript

JQuery has a built-in method to load a single js file. After loading is complete, you can perform subsequent operations in the callback function. The most basic method to use jQuery. getScript is as follows:
Copy codeThe Code is as follows:
JQuery. getScript ("/path/to/myscript. js", function (data, status, jqxhr ){

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

});

This getScript method returns a jqxhr, which you can use as follows:
Copy codeThe Code is as follows:
JQuery. getScript ("/path/to/myscript. js ")
. Done (function (){
/* Yes. No problem. What can I do here */
})
. Fail (function (){
/* Rely on and immediately perform the rescue operation */
});

The most common use of jQuery. getScript is to delay loading a js plug-in and execute it when loading is complete:
Copy codeThe Code is as follows:
JQuery. getScript ("jquery. cookie. js ")
. Done (function (){
JQuery. cookie ("cookie_name", "value", {expires: 7 });
});

Ii. cache Problems

There is a very important issue. When using jQuery. getScript, you need to use a timestamp string behind the js address 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, as shown below:

Copy codeThe Code is as follows:
JQuery. ajaxSetup ({
Cache: true
});

Copy codeThe 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 when loading scripts!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.