search
HomeWeb Front-endHTML TutorialRemember some browser caching things that you were not familiar with before_html/css_WEB-ITnose

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);                }            });        }    });}


Statement
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
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 <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

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 <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

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 <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

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.

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 <iframe> tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

How do I use the HTML5 <time> element to represent dates and times semantically?How do I use the HTML5 <time> element to represent dates and times semantically?Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 <time> element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What are the best practices for cross-browser compatibility in HTML5?What are the best practices for cross-browser compatibility in HTML5?Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How do I use HTML5 form validation attributes to validate user input?How do I use HTML5 form validation attributes to validate user input?Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools