Check browser's cache for a js file

前端 未结 4 1613
予麋鹿
予麋鹿 2020-12-25 09:22

How can I check for a javascript file in user\'s cache. If he refreshed the page or visits the site after sometime. I need not download that js file again. Does the js file

相关标签:
4条回答
  • 2020-12-25 09:27

    To check if a Javascript file is cached works only if the Javascript file is from the same domain afaik.

    You could then check it like this:

    try {
        await fetch("https://YOUR-DOMAIN.org/static/build/js/YOUR-FILE.js",
                 {method:'Head',cache:'only-if-cached',mode:'same-origin'});
    } catch (error) {
        console.error(error);
    }
    

    You will get a 200 back if it is cached, otherwise an error is thrown.

    0 讨论(0)
  • 2020-12-25 09:42

    The browser will take care of caching for you.

    When the cache is emptied depends partly on the browser settings and partly on the headers you send. If you set an Expires header, then the browser shouldn't re-request the file until it has expired. Reading about HTTP Headers might help you.

    0 讨论(0)
  • 2020-12-25 09:44

    The browser will automatically look after what it has in it's own cache. There are various mechanisms you can use for controlling it however.

    Look into the various HTTP caching headers, such as:

    • Last-Modified
    • Expires
    • ETag

    The Expires header is the most critical of these when it comes to client-side caching. If you set a far future Expires header (eg, 10 years) the browser will not (in theory) not look to the server again for that file. Of course then you need a method of changing the file name when the contents of the the file change. Most people manage this by adding a build number to the file path.

    0 讨论(0)
  • 2020-12-25 09:46

    Whether a javascript file is cached depends on how your web server is setup, how the users browser is setup and also how any HTTP proxy servers between your server and the user are setup. The only bit you can control is how your server is setup.

    If you want the best chance of your javascript being cached then you server needs to be sending the right HTTP headers with the javascript file. Exactly how you do that depends on what web server you are using.

    Here are a couple of links that might help:

    Apache - http://httpd.apache.org/docs/2.0/mod/mod_expires.html

    IIS - http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0fc16fe7-be45-4033-a5aa-d7fda3c993ff.mspx?mfr=true

    0 讨论(0)
提交回复
热议问题