2020年2月13日 星期四

[JS] RequireJS - Prevent JS File Caching

Problems
Very often when we updated the JS files, directly refreshing is not reflecting the changes, instead we need to manually clear cache, which makes end users using the web application quite annoying.


Solutions
RequireJS provides "cache busting" which can force browser to download the latest version of JS files every time new pages loaded

Basically, we write a general function accepting target path not to cache, the "require.config" will then execute the function, the bust function actually use current time and attach as the parameter of the JS URL, since time is always changing, it can force the browser to retrieve the JS files for every load


function bust(path) {
    return path + '?bust=' + (new Date()).getTime();
}

require.config({
    baseUrl: '/base/path',
    paths: {
        'fileAlias': bust('fileLikelyToChange'),
        'anotherFileAlias': bust('anotherFileLikelyToChange'),
        'jQuery': 'jQuery'
    },
});



References
https://stackoverflow.com/questions/16523755/cache-busting-specific-modules-with-requirejs

沒有留言:

張貼留言