Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs browser caching and loading chunk failed issue

Tags:

vue.js

I have a VueJS app. There is already open my site in one browser tab.

Now I am building new build for my app after some changes running npm run build which will creates a new set of dist/* files.

Now I am deploying this new build (after deleting the old build) on the server and accessing my app without refreshing page. At this time app trying to load files (may be from browser cache) from earlier version build which is no longer exist on server. So it's giving me error as shown in below image.

When I refresh the page or try to open in new tab of browser, it loads the new code no problem.

Please click here to show image

like image 846
Hardik Patel Avatar asked Oct 29 '25 02:10

Hardik Patel


1 Answers

This is the best answer I can find. Got this from https://blog.francium.tech/vue-lazy-routes-loading-chunk-failed-9ee407bbd58

The gist of it is in your router code, put

router.onError(error =>{    

    if (/loading chunk \d* failed./i.test(error.message) && navigator.onLine) {
        window.location.reload()
    }

}); // onError

I added the check for being online. He does warn though that this can potential get you in an infinite loop if the chunk really doesn't exist...

If this doesn't work, you may need to also add more of a global error handler. I had issues where my router file was missing when this scenario happened.

// Note: This is for when the Vue error handler doesn't kick in, otherwise, handled by the vue error handler.
            window.onerror = function(mMsg, mSource, mLineNo, mColNo, error){
                // mMsg = Char. Error Msg: i.e. "Uncaugh SyntaxError: Unexpected token '<'"
                // mSource = Char. i.e. 'https://yoursite.com/js/chunk-431587f6.ff603bf5.js'
                // mLineNo = Numeric. Line no
                // mColNo = Numeric. Col no
                // error = Object. Error object        
                if (mMsg.toLowerCase().indexOf("unexpected token '<'") >-1){
                    // this happens when a new update gets applies but my router.js file hasn't been pulled down for whatever reason. A page refresh fixes it. 
                    // mSource = 
                    if (navigator.onLine){
                         window.location.reload();
                    }
                }

            }; // window.onerror
like image 187
ScottR Avatar answered Oct 31 '25 06:10

ScottR