Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent jQuery.getScript adding ?_=timestamp

How to prevent jQuery.getScript from adding ?_=timestamp on URLs?

error log

Source code:

$.getScript('/js/ace/ace.js',function(res) {
   // do something
}); 
like image 553
Kokizzu Avatar asked Jun 24 '26 16:06

Kokizzu


2 Answers

This seems to be related to $.getScript('/js/ace/ace.js',function...) calls.

You can consider adding the following snippet as high up as possible:

$.ajaxSetup({
    cache: true
});  

Putting the cache: true in your $.ajax() doesn't affect $.getScript('/js/ace/ace.js',function...)
in any way and that's what visible in that screenshot.

Another way, as described at jQueryByExample:

(1) before making call to $.getScript method, you can set the cache true for ajax request and set it to false once script is loaded.

//Code Starts
//Set Cache to true.
$.ajaxSetup({ cache: true });
$.getScript(urlhere, function(){
    //call the function here....
    //Set cache to false.
    $.ajaxSetup({ cache: false });
});
//Code Ends

(2) All you need to do is to add a boolean parameter, which will set the cache attribute to true or false. That's the beauty of jQuery that you can redefine things the way you need.

//Code Starts
$.getScript = function(url, callback, cache){
$.ajax({
    type: "GET",
    url: url,
    success: callback,
    dataType: "script",
    cache: cache
    });
};

So,now you call the $.getScript like, (notice the 3rd argument)

//Code Starts
$.getScript('js/jsPlugin.js',function(){
   Demo(); //This function is placed in jsPlugin.js
}, true);
//Code Ends
like image 198
Vikrant Avatar answered Jun 27 '26 06:06

Vikrant


I made another aprouch using promises, based on previous responses, think that's more interesting.

window.loadScripts = (scripts) =>  {
    return scripts.reduce((currentPromise, scriptUrl) => {
        return currentPromise.then(() => {
            return new Promise((resolve, reject) => {
                var script = document.createElement('script');
                script.async = true;
                script.src = scriptUrl;
                script.onload = () => resolve();
                document.getElementsByTagName('head')[0].appendChild(script);
            });
        });
    }, Promise.resolve());
};

Let's play

var scripts = [
    "app/resources/scriptDoSomething.js",
    "app/resources/somethingElse.js"
];

loadScripts(scripts).then(() => {
  alert('All scripts were loaded!');
});
like image 30
Klaus Etgeton Avatar answered Jun 27 '26 05:06

Klaus Etgeton