防止jQuery.getScript添加?_ = timestamp

Kok*_*zzu 1 javascript jquery

如何防止jQuery.getScript添加?_=timestampURL?

错误日志

源代码:

$.getScript('/js/ace/ace.js',function(res) {
   // do something
}); 
Run Code Online (Sandbox Code Playgroud)

Vik*_*ant 7

这似乎与$.getScript('/js/ace/ace.js',function...)电话有关.

您可以考虑尽可能高地添加以下代码段:

$.ajaxSetup({
    cache: true
});  
Run Code Online (Sandbox Code Playgroud)

放置缓存:true在你的内容$.ajax()中不会$.getScript('/js/ace/ace.js',function...)
以任何方式影响,这就是截图中可见的内容.

另一种方式,如jQueryByExample所述:

(1)在调用$.getScript方法之前,可以为ajax请求设置缓存true,并在加载脚本后将其设置为false.

//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
Run Code Online (Sandbox Code Playgroud)

(2)您需要做的就是添加一个boolean参数,该参数将cache属性设置为true或false.这jQuery就是你可以按照自己需要的方式重新定义事物的美妙之处.

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

所以,现在你打电话给那个$.getScript,(注意第三个参数)

//Code Starts
$.getScript('js/jsPlugin.js',function(){
   Demo(); //This function is placed in jsPlugin.js
}, true);
//Code Ends
Run Code Online (Sandbox Code Playgroud)


Kla*_*ton 6

根据之前的回复,我使用 Promise 进行了另一次访问,认为这更有趣。

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());
};
Run Code Online (Sandbox Code Playgroud)

让我们玩

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

loadScripts(scripts).then(() => {
  alert('All scripts were loaded!');
});
Run Code Online (Sandbox Code Playgroud)