Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding jQuery $.getScript()

Tags:

jquery

I use getScript to load dynamically my plugin:

$.getScript('js/code.photoswipe.jquery-3.0.4.min.js', function () {
   //do magic
});
  1. How do I disable caching busting? At the moment it generates numbers at the end: js/code.photoswipe.jquery-3.0.4.min.js?_=1326992601415 I saw this, but not sure how to use it in my case:

    $.getScript = function (url, callback, cache) {
       $.ajax({
          type: "GET",
          url: url,
          success: callback,
          dataType: "script",
          cache: cache
       });
    };
    
  2. If I call $.getScript multiple times adding the same js file, does it do request each time to get that file? If so, is there a way to check if we already imported that script, so we could avoid calling getScript again for the same file?

like image 858
Stewie Griffin Avatar asked Jan 19 '12 16:01

Stewie Griffin


People also ask

How does jQuery getScript work?

jQuery | getScript() MethodIt holds the url to whom the request is send to. success(response, status): It is optional parameter. It holds the function to run if the request got success. response: It holds the result data from the request.

How do you check if a script is loaded with JavaScript?

Pass the URL of JavaScript file in a <script> tag. Set the onload parameter, Trigger alert if script loaded. If not then check for loaded variable, if it is equal to false, then script not loaded.

Is not defined in jQuery?

You may experience the “jQuery is not defined error” when jQuery is included but not loaded. Make sure that it's loaded by finding the script source and pasting the URL in a new browser or tab. The snippet of text you should look for to find the URL to test.

What is jQuery HTML?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.


2 Answers

The jQuery docs for $.getScript say that getScript is shorthand for:

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

http://api.jquery.com/jQuery.getScript/

This means that you just need to add a cache : true parameter to that.

$.ajax({
  url: url,
  cache : true,
  dataType: "script",
  success: success
});

Simple as that. The getScript function is nothing special, just shorthand.

like image 178
Kieran Avatar answered Oct 04 '22 09:10

Kieran


1 . jQuery 1.12.0 and later supports the options object signature:

$.getScript({
    url: "foo.js",
    cache: true
})

2 . Assuming you set cache:true the file will be loaded from the browser cache (unless browser cache is disabled or expired, for example when devtools is open)

like image 20
oriadam Avatar answered Oct 04 '22 09:10

oriadam