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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

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.

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 to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

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

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

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 &lt;time&gt; 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 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

See all articles