简体   繁体   中英

Caching issue js files using requirejs

I keep having issues with the cached js files, which causes the user to not have the latest js and the browser to give js errors on files it can't find that should be included with requirejs.

My requirejs (version 2.3.6) setup is as follows:

<script src="{% static 'main/js/require.js' %}"></script>
<script>
function requireConfig(urlArgs) {
    requirejs.config({
            baseUrl: '/static/main/js/',
            urlArgs: urlArgs,
            waitSeconds: 15,
            packages: [{
                name: 'moment',
                location: '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0',
                main: 'moment'
            }],
            paths: {
                // vendors
                'jquery': '//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min',
                'jquery_ui': '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min' ,
                'text_contrast': './vendors/text_contrast',
            },
            shim: {
                'jquery_ui': {
                    deps: ['jquery']
                },
                'text_contrast': {
                    exports: 'hex',
                },
            }
    });
}
</script>
<script type="text/javascript">
    requireConfig("bust=v18");
    require(['platform/init'], function (m) {
        m.init({
            debug: {{ debug|yesno:"true,false" }},
        });
    });
</script>

I include this before the closing body tag. Whenever the user refreshes the page after clearing his cache, all (new) js files with the bust argument are loaded correctly. The problemen is, I cant force my users to clear its cache everytime I deploy some new js.

Update

If I add +(new Date()).getTime() to the requireConfig function, the files now get the time argument, which seems to work. But on some urls the browser still looks for a js file at the wrong path. For example when I go to an url it loads:

/static/main/js/text_contrast.js?bust=v181560938449189 

which gives a 404. After clearing my cache and a reload the file is found at:

/static/main/js/vendors/text_contrast.js?bust=v181560939213670

This seems to occur on urls I've already loaded in the past with that wrong path pointing to the text_contrast.js file

You can add time stamp to the urlArgs in the requirejs.config object so that url's will not be cached.

One way you can do it is by changing your code from

requireConfig("bust=v18");

to

requireConfig("bust=v18"+(new Date()).getTime());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM