Load the JavaScript scripting solution asynchronously using jQuery

  • 2020-03-30 02:40:15
  • OfStack

JavaScript loaders are powerful and useful tools in Web development. Several popular loaders, such as curljs, LABjs, and RequireJS, are widely used. They are powerful, but in some cases can have simpler solutions.

If you're using jQuery, there's a built-in way to load scripts. You can use this method if you want to lazily load a plug-in or any other type of script. Here's how to use it.

Implementation method

JQuery has a getScript method built in to load a script, and there are several ways to handle the returned results. The basic usage of jQuery. GetScript looks like this:
 
jQuery.getScript("/path/to/myscript.js", function(data, status, jqxhr) { 

 

}); 

The getScript method returns a jqXHR object, so you can use it like this:
 
jQuery.getScript("/path/to/myscript.js") 
.done(function() { 
 
}) 
.fail(function() { 
 
}); 

The most common scenario for using jQuery. GetScript is to lazily load a plug-in and call it after loading:
 
jQuery.getScript("jquery.cookie.js") 
.done(function() { 
jQuery.cookie("cookie_name", "value", { expires: 7 }); 
}); 

If you need to do more advanced things like load multiple scripts and different types of files (text files, images, CSS files, etc.), I recommend switching to a more powerful JavaScript loader. GetScript is perfect if you just want to lazily load the plug-in instead of simply loading it on every page!

The cache problem

Note that when using jQuery. GetScript, a timestamp is automatically added to the script URL to make the script uncached. So you need to set up all requests to cache scripts:
 
jQuery.ajaxSetup({ 
cache: true 
}); 

If you don't want to override all caching and your AJAX requests, it's best to use the jquery.ajax method and set the dataType to script, for example:
 
jQuery.ajax({ 
url: "jquery.cookie.js", 
dataType: "script", 
cache: true 
}).done(function() { 
jQuery.cookie("cookie_name", "value", { expires: 7 }); 
}); 

Pay special attention to caching when loading scripts!

Related articles: