Home > Web Front-end > HTML Tutorial > Remember some browser caching things that you were not familiar with before_html/css_WEB-ITnose

Remember some browser caching things that you were not familiar with before_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:39:14
Original
1231 people have browsed it

Browser caching, I have read a lot of information on this before, and I always thought it was something that should be handled by operation and maintenance. I have never done it myself, so I don’t understand it deeply and it is easy to forget.

I recently took a look at nodejs as a static server and gained a little in-depth understanding, so I took notes


Some articles I read

cache-control, Expires ,Last-Modified

Cache process

Simple implementation of nodejs


Some articles I read

https://developers.google. com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=zh-cn

http://www.laruence.com/2010/03/05/1332.html

http://www.alloyteam.com/2012/03/web-cache-2-browser-cache/

https://cnodejs.org/topic/ 4f16442ccae1f4aa27001071


cache-control,Expires,If-Modified-Since,last-modified

Some commonly used things to set cache in request headers and response headers

Expires

The Expires header field provides a date and time after which the response is considered expired. Invalid cache entries are usually not cached

The Expires field receives a value in the following format: "Expires: Sun, 08 Nov 2009 03:37:26 GMT" For example, if I want to set a time of 30 days, this is what is in nodejs Such new Date(new Date().getTime() 60*60*24*30).toUTCString()

This should be used in conjunction with Last-Modified

when the requested file , is cached in the browser. The next time you request, if you enter the address directly in the browser, the request will not be sent

If you force ctrl R, the request will be sent, and the server will make the request according to the request Compare the Last-Modified header with the modification time of the requested file. If there is no modification, return 304, which will not return the file to the client, saving bandwidth. The client finds that the returned file is 304, and reads the file from the browser

Supported since http/1.0

If there is cache-control max-age, it will override Expires


cache-control

This has many values ​​​​that can be set , I can understand that there are only 4 no-cache, max-age, public, private

no-cache

This is easy to understand, but it is not cached

max- age

is set to a number of seconds. During this time, no request will be sent to the server. If a refresh is forced, 304 will be returned, the same as Expires.

The format is as follows Cache-Control:max-age =315360000

public

The response will be cached and shared among multiple users

private

The response can only be cached privately and cannot be used by other users shared between. For example, when the POST form is submitted, it will help you retain the filled-in content, indicating that each user has a cache


Last-Modified

Last-Modified stores the last modification of the file. The time

is in the following format: last-modified: Thu, 23 Jul 2015 08:50:29 GMT

This is set in the response header

if-modified-since

The browser receives the Last-Modified from the server and records it. The next time it sends a request, the request header contains if-modified-since, and its value is the value returned by the previous Last-Modified

The caching process

It’s just my personal understanding, and it may not always be correct. The static server is processed with nodejs


1. When the browser visits for the first time time, all files must be downloaded

2. When the server receives the request, if the request is for static resources (temporarily specifying pictures, styles, and js as static resources), write in the return header Enter Last-Modified, Expires, Cache-Control. Last-Modified tells the last modification time of the file. Expires and Cache-Control tell the browser that these files can be cached in the browser

3. Visit the browser again If this address is entered directly in the browser, the cached file request will not be sent, as shown in the figure

4. If you force refresh (ctrl r), then The request will be sent. When it reaches the server, it will compare the last-modified of the file based on the if-modified-since passed in the request header. If there is no modification, the file content will not be returned and status code 304 will be returned, as shown in the figure


Simple implementation of nodejs

var http = require("http");var fs   = require("fs");var url  = require("url");var querystring = require("querystring");http.createServer(function(req,res){    var gurl = req.url,        pathname = url.parse(gurl).pathname;    if( pathname.indexOf("favicon.ico")>=0){        var ico = fs.readFileSync("./favicon.ico");        res.writeHead(200,{            "Content-Type" : "image/x-icon"        })        res.end(ico);        return;    }    if(pathname.indexOf("/static/")==0){        var realPath = __dirname + pathname;        dealWithStatic(pathname,realPath,res,req);        return;    }}).listen(5555);function dealWithStatic(pathname,realPath,res,req){    fs.exists(realPath,function(exists){        if(!exists){            res.writeHead(404,{                "Content-Type" : "text/html"            });            res.end("not find!!!");        }else{            var mmieString = /\.([a-z]+$)/i.exec(pathname)[1],                cacheTime  = 2*60*60,                mmieType;            switch(mmieString){                case "html" :                case "htm"  :                case "xml"  : mmieType = "text/html";                break;                case "css"  : mmieType = "text/css";                break;                case "js"   : mmieType = "text/plain";                break;                case "png"  : mmiType  = "image/png";                break;                case "jpg"  : mmiType  = "image/jpeg";                break;                                default     : mmieType = "text/plain";            }            var fileInfo      = fs.statSync(realPath),                lastModied    = fileInfo.mtime.toUTCString(),                modifiedSince = req.headers['if-modified-since']            if(modifiedSince && lastModied == modifiedSince){                res.writeHead(304,"Not Modified");                res.end();                return;            }            fs.readFile(realPath,function(err,file){                if(err){                    res.writeHead(500,{                        "Content-Type" : "text/plain"                    });                    res.end(err);                }else{                    var d = new Date();                    var expires = new Date(d.getTime()+10*60*1000);                    res.writeHead(200,{                        "Content-Type"  : mmieType,                        "Expires"       : expires.toUTCString(),                        "Cache-Control" : "max-age=" + cacheTime,                        "Last-Modified" : lastModied                    });                    res.end(file);                }            });        }    });}
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template