Table of Contents
Some articles I read
cache-control,Expires,If-Modified-Since,last-modified
The caching process
Simple implementation of nodejs
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

Jun 24, 2016 am 11:39 AM

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


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles