Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get script file by $.getScript() [closed]

I am trying to imported some javascript files from some code hosts.

    $.when(
        $.getScript('http://pingzi.googlecode.com/svn-history/r30/branches/wangqi/web/jquery.window.min.js'),
        $.getScript('http://mottie.github.com/tablesorter/js/jquery.tablesorter.js'),
        $.getScript('http://tconnell.com/samples/scroller/lib/jquery.tablesorter.scroller.js'),
        $.getScript('http://code.highcharts.com/stock/highstock.js'), 
        $.Deferred(
            function(deferred) { 
                $(deferred.resolve);
            }
        )
    ).done(function() {  
       // my function goes here....
    });

When I try to call these URLs to import js files, the URLs will append ?_=1344036242417 and then I could not actually get to the script file I want.

i.e. "NetworkError: 404 Not Found - http://pingzi.googlecode.com/svn-history/r30/branches/wangqi/web/jquery.window.min.js?_=1344036242417"

Any one have ideas how to bypass this problem? Thank you in advance.

like image 244
sozhen Avatar asked Aug 03 '12 23:08

sozhen


3 Answers

That's because caching in ajax is turned off by default in jQuery, to turn it on and remove the querystring do :

$.ajaxSetup({ 
    cache: true 
}); 

but that could also affect other ajax calls that you don't want to cache, there's a lot more on this in the docs for getScript, and there's even a little how-to on creating a cached getScript function called cachedScript.

You can also enable caching in $.getScript by redefining the function with a new option to turn the cache on/off by passing true or false :

$.getScript = function(url, callback, cache){
    $.ajax({
            type: "GET",
            url: url,
            success: callback,
            dataType: "script",
            cache: cache
    });
};
like image 141
adeneo Avatar answered Oct 19 '22 13:10

adeneo


jQuery have an automatic caching mechanism for such queries. If you do not want the extra param to be added use following setup:

$.ajaxSetup({
  cache: true
});

Source: http://api.jquery.com/jQuery.getScript/#caching-requests

like image 5
Łukasz W. Avatar answered Oct 19 '22 12:10

Łukasz W.


jQuery is automatically adding the _=1344036242417, which breaks the URL. Note:

  • Without the query param, the URL is fine
  • But it 404s with the query param

To prevent jQuery from adding that parameter: Ajax get request with useless parameter. To summarize that answer, use $.ajaxSetup before calling $.getScript() to set cache: true.

Be [sic] default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

$.ajaxSetup({
    cache: true
});
like image 4
Matt Ball Avatar answered Oct 19 '22 11:10

Matt Ball