Dynamic loading of js script files using jQuery

  • 2020-03-30 02:31:20
  • OfStack

They're powerful, but sometimes they don't pay off. If you're using jQuery, there's a built-in way to load a single js file. Use this method when you need to lazily load some js plug-ins or other types of files. Here's how to use it!

JQuery getScript() method loads JavaScript

JQuery has a built-in method to load a single js file. When the load is complete, you can perform subsequent operations in the callback function. The most basic way to use jQuery. GetScript is this:


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

This getScript method returns a JQXHR, which you can use as follows:

jQuery.getScript("/path/to/myscript.js")
 .done(function() {
  
 })
 .fail(function() {
  
});

The most common place to use jquery.getscript is to lazily load a js plug-in and execute it when the load is complete:


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

Second, the cache problem


jQuery.ajaxSetup({
  cache: true
});


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

Be careful of caching when loading scripts!


Related articles: