简体   繁体   中英

Browser used cache without revalidate

I am trying to learning the browser's (Chrome/Firefox) cache mechanism. I set up a simple HTML:

    <HTML><BODY>
    Hellow World

    <script>
        function loadJS(){ 
           var s = document.createElement('script'); 
           s.setAttribute('src','/myscript');
           document.body.appendChild(s);
        } 
        loadJS()
    </script>

    <BODY></HTML>

I output " Cache-Control: max-age:30 " for "/myscript"

Everytime I press F5, browser will re-validate /myscript with my server to get a 304 back.

But if I use

setTimeout(loadJS, 1);

Everytime I press F5, it looks like browser will check expire time, and if not expired, browser will use the cache directly instead of going to server for revalidation.

My question is:

  1. Why? is there a detail explanation for this?
  2. Does it mean if I want browser to use cache and reduce network request as much as possible, I need to wait the page loaded, and then request resources by js later?

I've done a fair amount of experimentation with browser cache control, and I am surprised that no one has posted an answer.

Many people do not pay attention to this. As a results websites--for no reason at all--make browsers perform useless roundtrips for a 304-not modified on images, js or css files which are unlikely changed in 5 years--like who is going to change jquery.v-whatever?

So anyway, I have found that when you hard refresh the browser using F5 or ctrl-r, Chrome will revalidate just about everything on the page--as it should. This is very helpful and is why you want keep the etags in the response header.

When testing your max-age and expires headers, browse the site as a user naturally would by clicking the links on the page. Watch the web server's logfile (I use http://www.apacheviewer.com ) and you'll get a good idea of how the browsers are caching.

Setting the headers works. I posted this a while back: Apache: set max-age or expires in .htaccess for directory

The easiest way for me to manage the web server is to create a /cache directory and instruct apache to set a 1 year max-age and expires header for everything in every subdir.

It works wonders. My pages make 1 round trip to the server, where as they used to make 3-5 trips with each request, just to get a 304.

Write your html as you normally would. The browsers will obey the cache settings in the headers.

Just know that hard refreshing the browser causes the browser to ignore max-age and relies on etags.

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