SoFunction
Updated on 2025-02-28

Methods to dynamically load js script files using jQuery

They are powerful, but sometimes they can be worth the effort. If you are using jQuery, it has a built-in method to load a single js file. This method can be used when you need to delay loading some js plugins or other types of files. Here is a description of how to use it!

1. jQuery getScript() method loads JavaScript

jQuery has a built-in method to load a single js file; after the loading is completed, you can perform subsequent operations in the callback function. The most basic method to use is as follows:

Copy the codeThe code is as follows:

("/path/to/", function(data, status, jqxhr) {

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

});


This getScript method returns a jqxhr, which you can use as follows:
Copy the codeThe code is as follows:

("/path/to/")
 .done(function() {
/* Yeah, no problem, what can I do here */
 })
 .fail(function() {
/* Damn, perform the rescue operation immediately */
});

The most common use is to lazy load a js plugin and execute it when the load is complete:

Copy the codeThe code is as follows:

("")
 .done(function() {
  ("cookie_name", "value", { expires: 7 });
});

2. Caching issues

There is a very important problem. When using it, you need to use a timestamp string to follow 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 the codeThe code is as follows:

({
  cache: true
});

Copy the codeThe code is as follows:

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

Be sure to be careful when loading scripts!