This article mainly introduces the relevant knowledge of localStorage's black technology-js and css caching mechanism, which has certain reference value. Let's take a look at it together
1. The cause of discovering black technology
I saw a technical blog post on the WeChat public account today and wanted to use Evernote to collect it, so I sent the article link to my PC. Then I habitually open the console, look at the source code, and want to know what new technologies WeChat has recently used.
Haha, the following aroused my desire to be a detective. The abnormal point after the page is loaded is that only one js is loaded, as shown in the following figure:
I am very surprised, why has Disable cache been turned on and only one js is loaded? And it’s so small. Then, I held down Ctrl O to search for resource files and found that I had been "fooled". In fact, there is more than one js file at all.
An idea flashed in my head. Could it be that I used localStorage to cache it? ! I quickly took a look at localStronge, and it was true. . . .
My heart was surging. Isn’t this the idea of optimizing loading performance that I wanted to achieve before! Darling, I am ignorant, a front-end team has already implemented the code.
2. Let’s talk about the optimization ideas for file loading
Usually, the front-end resource file loading optimization is to load as many files as possible without modifying and iterating the file. Make optimal use of caching to avoid downloading the same file multiple times.
The general approach is to extend the validity period of the resource as much as possible, that is, set the max-age in Cache-Control so that the return code of the page resource request is 304, so that the browser can directly use the local cache.
Although the negotiation cache (304) on the PC side is very fast, due to network reasons, the negotiation cache effect on the mobile side is not as good as that on the PC side. Moreover, the phone will frequently clear the local cache, so the file cache time will not be very long.
At this time, localStorage comes in handy.
Compared with cookies, localStorage can cache large volumes of data and is permanently valid. Therefore, if you store js resources and css resources in localStorage, you can save the time spent sending http requests and greatly improve the user's browsing experience.
3. Problems that need to be solved when using localStorage for resource caching
##3.1 Version update mechanism
As long as a project is still under iterative development, it is inevitable to update resource files. Ordinary resource requests can be based on file name md5 http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/moon32ebc4.jsor Add a specific suffix after the resource link http://1.ss.faisys.com/js/comm/fai.min.js?v=201612051739 Make a mark to determine whether resources need to be updated. If you use localStorage, you need a new cache update mechanism.
3.2 Build a scaffolding to update the code
If you use localStorage cache, you need a new scaffolding to manage the reading and writing of resource files. .3.3 The background outputs a resource configuration information
Because the front-end needs to update resources, the background needs to output a basis for the front-end to make judgments Use, that is, a piece of resource configuration information is required. The front end performs matching and comparison based on the configuration information, and finally decides whether to use localStorage cache or re-initiate the request to download the latest resource file.3.4 There are XSS security risks
The client can modify the information in localStorage at will. If any hacker wants to practice, he can inject js code at will. Then, when the page is refreshed, the injected code will also be executed.4. Analysis of WeChat practices
4.1 Version identification
4.2 Scaffolding
It can be seen that WeChat uses the scaffolding moon.js developed by itself. The actual file name in this webpage is It's moon32ebc4.js.Because it is a file with obfuscated variable names, it is a bit difficult to see the direction of the specific code, so I will not analyze it here.
4.3 Resource configuration information
Because the scaffolding moon.js requires resource configuration information to work properly, the configuration information must be in moon.js output before.
Looking at the script tags before moon.js in turn, I found the json object window.moon_map.
Use the console to output this variable to view the information as follows:
Seeing this, one point can be made clear: this It is the resource configuration information table necessary for the update mechanism.
Moreover, it can be seen that the key of the configuration information json object corresponds to the key in localStorage. In the same way, value values also correspond to one-to-one.
4.4 XSS attack
This is to verify whether there is an XSS attack on WeChat’s caching mechanism. Don’t see the children’s shoes here. To do bad things.
I inserted alert("hehe"); in a js cache code to see if the pop-up window will appear when the page is refreshed to verify whether there is an attack vulnerability.
After refreshing the page, the result is as follows:
It can be seen that WeChat has not solved this kind of problem. Therefore, this caching mechanism still has inherent shortcomings.
4.5 Test the update mechanism of WeChat
Modify the key in localStorage __MOON__a/a_report.js_verCorresponding value, let WeChat’s scaffolding moon.js update __MOON__a/a_report.js, and erase the code I just actively inserted.
Here, I changed the file name to ***587.js (the original file name was ***586.js). Then F5 refreshes the page.
The result is: report.js code has been updated, and the version number has been restored to ***586.js.
5. Conclusion
localStorage cache has its place, but it is not a panacea. You need to pay attention to the pitfalls mentioned above.
I can summarize the applicable scenarios into the following points:
1. CSS files required for non-first-screen rendering can be cached in LS.
The css required for first-screen rendering needs to be output in a conventional way because it is required by SEO. Otherwise, when crawlers crawl the page, the page effect will be very poor. For non-first-screen CSS, you can use LS caching to reduce resource download time.
2. Codes that are not the main business logic, such as display classes and animation classes, can be cached in LS.
In this way, security vulnerabilities in the business layer can be avoided to a certain extent. Of course, no matter how the front end is protected, it is only a thin layer of paper. What is important is that the backend interface must be securely protected.
3. The mobile terminal can do LS caching. LS caching on the PC side has little optimization effect.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to write JS and CSS in the same file
About native js implementation Single page/full screen scrolling method similar to fullpage
The above is the detailed content of Introduction to the caching mechanism of js and css. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),