JQuery and script caching

2019-09-05 23:21发布

I'm experiencing a rather bizarre behaviour in JQuery.

I'm dynamically loading a series of scripts using this code:

for (var i=0; i<requiredScripts.length; i++)
    {
    $.ajax({
        url: baseURL+"js/"+requiredScripts[i],
        async: false,
        dataType: 'script',
        success: checkLoaded
        });
    }

The checkLoaded function just increments a counter, so that when all of the scripts have been loaded it executes certain functions.

Everything was working fine until I uploaded a newer version of one of the loaded scripts. JQuery seems to continue loading the old one. I tried refreshing (and force refreshing) the page in vain...

So I disabled the cache (from the WebDeveloper toolbar) and now the script magically loads. But when I reenabled the cache the old script came back...

I went as far as deleting the file from the server, and that did not do anything! (unless I disable the cache, that is).

I'm sure I'm just missing something really simple, but I could not figure it out.

Thanks in advance to anyone who can help.

EDIT: just to clarify, I do want the file to be cached. What I don't understand is why a force refresh of the page does not result in getting the new script.

Also, note that this only happens if I load the files with JQuery, if I add them manually in the HTML a force refresh loads the new page.

EDIT #2: solved by deleting the cache from FF. Still, don't understand why a CTRL+SHIFT+R did not do the trick...

3条回答
三岁会撩人
2楼-- · 2019-09-05 23:43

You can simply use the classic caching disabling method.

var cd=+new Date();
for (var i=0; i<requiredScripts.length; i++)
    {
        $.ajax({
            url: baseURL+"js/"+requiredScripts[i]+"?"+cd,
            async: false,
            dataType: 'script',
            success: checkLoaded
            });
    }

In this way the script url is always different and you are sure that its content is not cached.

查看更多
不美不萌又怎样
3楼-- · 2019-09-05 23:47

Tell apache to sent no-cache headers for your JS files:

<Directory "/path/to/baseURL/js">
    Header Set Cache-Control "max-age=0, no-store"
</Directory>
查看更多
疯言疯语
4楼-- · 2019-09-05 23:51

$.ajax has a cache option that does the same thing as mck89's answer but is a little neater:

$.ajax({
    url : 'example.com',
    cache : false,
    ....
});
查看更多
登录 后发表回答