Search code examples
javascriptcachingsrc

What makes a source script not loading and then loading again?


When using a <script> tag with src attribute one should expect it to download:

<script src="https://unpkg.com/neovis.js@2.0.0-alpha.9/dist/neovis.js"></script>

However recently it fails to download, and I fail to locate the reason why it becomes so. The possibly reliable fix is that when that happens, I change it to:

<script>
function cdnLoaded() {
    console.log('loaded');
}
function cdnError() {
    console.log('not loaded');
    // do error handling here
}
</script>    
<script onload="cdnLoaded()" onerror="cdnError()" async src="https://unpkg.com/neovis.js@2.0.0-alpha.9/dist/neovis.js"></script>

At this point, the console says it's loaded but actually it's not. But after that when I revert it back to:

<script src="https://unpkg.com/neovis.js@2.0.0-alpha.9/dist/neovis.js"></script>

then it works again. This has happened twice in two browsers (Edge and Firefox), and I haven't had a chance to test it again.

What can be the reason for this strange behavior? Could this be a kind of caching?


Solution

  • Browser cache scripts by filename. Probably adding/removing onload and onerror properties force the browser to download the script again.

    To force file reload you could apply a versioning

    <script src="util.js?v=1"></script>
    

    Modern frameworks use to join, minify and rename script file automatically. You can do it with tools like webpack