Home > Web Front-end > JS Tutorial > body text

HTML5 web caching and application caching

小云云
Release: 2018-01-13 11:13:07
Original
1573 people have browsed it

This article mainly introduces HTML5 Web caching and application caching (cookie, session). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Before introducing HTML5 web caching, let’s get to know cookies and sessions:

session:

Because HTTP is Status, who are you? What did you do? Sorry, the server doesn't know.

So session appears, which stores user information on the server for future use (such as user name, shopping cart purchases, etc.).

But the session is temporary and will be deleted when the user leaves the website. If you want to store information permanently, you can save it in a database!

Session works: Create a session id (core!!!) for each user. The session id is stored in the cookie, which means that if the browser disables cookies, the session will become invalid! (But it can be implemented in other ways, such as passing session id through URL)

User authentication generally uses session.

Cookie:

Purpose: Data (usually encrypted) stored locally on the client side by the website to mark the user's identity.

  1. When a user visits a webpage, the name is recorded in the cookie;

  2. The next time the user continues to visit the webpage, the user can be read from the cookie Access to records.

The cookie will be carried (even if not needed) in the http request from the same origin, that is, passed back and forth between the client and the server!

The data size of the cookie does not exceed 4k

Validity period of cookie: The set cookie is valid until the expiration time, even if the browser is closed!

localStorage & sessionStorage:

In the early days, cookies were commonly used for local cache, but web storage needs to be safer and faster!

These data will not be saved on the server (stored on the client) and will not affect server performance!

sessionStorage and localStorage data storage also have size limits, but they are much larger than cookies and can reach 5M or even larger!

localStorage: Data storage without time limit!

sessionStorage: As you can see from the English meaning, it is the data storage of the session, so after the user closes the browser (tab/window), the data is deleted!

HTML5 web storage support:

IE8 or above, modern browser.

Data is stored in key-value pairs:

localStorage and sessionStorage have the following methods:

  1. ##localStorage.setItem(key, value): Set (save) data; equivalent to localStorage.key=value!

  2. localStorage.getItem(key): Get data

  3. localStorage.removeItem (key): Delete a single data

  4. localStorage.clear(): Delete all data

  5. localStorage.key(index): Get a certain Index key value


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>web storage</title>
</head>

<body>
    <p id="test"></p>
    <script>
        if (typeof (Storage) != undefined) {
            localStorage.name = &#39;xiao ming&#39;;
            localStorage.setItem(&#39;name1&#39;, &#39;Apple&#39;);
            document.getElementById(&#39;test&#39;).innerHTML = "you are: " + localStorage.name;
            console.log("first:" + localStorage.name1 + "," + localStorage.key(0));
            localStorage.removeItem(&#39;name1&#39;);
            console.log("second: " + localStorage.name1);
            console.log("third: " + localStorage.getItem(&#39;name&#39;));
            localStorage.clear();
            console.log("last:" + localStorage.name);
        } else {
            document.getElementById(&#39;test&#39;).innerHTML = "更新浏览器吧!目前浏览器不支持stroage";
        }
        
    </script>
</body>
</html>
Copy after login

Program running result:

Note: key value pair It is saved as a string, and the type should be changed according to requirements (for example, when adding, it becomes Number type).

HTML5 Application Cache:

By creating a cache manifest file, web applications can be cached and can be accessed without network status!

Application Cache advantages:

1. Offline browsing;

2. Faster speed: cached resources are loaded faster;
3. Reduce browsing Server load: The client will only download or update changed resources from the server

Support:

IE10 or above, modern browsers.

Usage:


<!DOCTYPE html>
<html manifest="demo.appcache">
</html>
Copy after login

Note: To enable the application cache, you need to specify the manifest attribute (extension: .appcache); if the manifest attribute is not specified, the page It will not be cached (unless the page is directly specified in the manifest file!)

The manifest file must be correctly configured on the server with MIME-type: text/cache-manifest.

Manifest file:

The manifest is a simple text file that tells the browser what is cached and what is not cached!

The manifest can be divided into three parts:

CACHE MANIFEST: The files listed in this item will be cached after the first download!

NETWORK: The files listed in this item require a network connection with the server and will not be cached!

FALLBACK: This item lists the fallback page when the page cannot be accessed (such as: 404 page)!

test.appcache:


CACHE MANIFEST
#2017 11 21 v10.0.1
/test.css
/logo.gif
/main.js

NETWORK
/login.php
/register.php

FALLBACK
#/html/目录中文件无法访问时,用/offline.html替代
/html/ /offline.html
Copy after login

Update application cache: 1. The user clears the browser cache!
2. The manifest file is changed (#: indicates a comment, and if it is changed to #2018 1 1 v20.0.0, the browser will re-cache!)
3. The program updates the application cache!

Web Workers:

Web workers are javascript running in the background, independent of other scripts and will not affect page performance!

When executing a script on a general HTML page, the page will not respond unless the script is loaded!

支持情况:IE10以上,现代浏览器

示例:html文件:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>web worker</title>
</head>
<body>
    <p>计数:<output id="count"></output></p>
    <button onclick="startWorker()">开始</button>
    <button onclick="overWorker()">结束</button>

    <script>
        var w;
        function startWorker(){
            // 检测浏览器是否支持web worker
            if(typeof(Worker)!==&#39;undefined&#39;){
                if(typeof(w)==&#39;undefined&#39;){
                    //创建web worker对象
                    w=new Worker(&#39;testWorker.js&#39;);
                }
                // 事件持续监听(即使外部脚本已经完成),除非被终止
                w.onmessage=function(event){
                    document.getElementById(&#39;count&#39;).innerHTML=event.data;
                };
            }else{
                document.getElementById(&#39;count&#39;).innerHTML=&#39;浏览器不支持web worker&#39;;
            }
        }
        function overWorker() {
            // 终止web worker对象,释放浏览器/计算机资源
            w.terminate();
            w=undefined;
        }
    </script>
</body>
</html>
Copy after login

testWorker.js文件:


var i=0;
function timedCount() {
    i+=1;
    // 重要的部分,向html页面传回一段信息
    postMessage(i);
    setTimeout(&#39;timedCount()&#39;,500);
}
timedCount();
Copy after login

注意1:通常web worker不是用于如此简单的任务,而是用在更耗CPU资源的任务!

注意2:在chrome中运行会产生“cannot be accessed from origin 'null'”的错误,我的解决方法是:xampp中开启apache,用http://localhost/进行访问。

web worker缺点:

由于web worker位于外部文件中,所以它无法访问下列javascript对象:

  1. window对象;

  2. document对象;

  3. parent对象。

HTML5 server-sent events(服务器发送事件):

server-sent事件是单向信息传递;网页可以自动获取来自服务器的更新!

以前:网页先询问是否有可用的更新,服务器发送数据,进行更新(双向数据传递)!

支持情况:除IE以外的现代浏览器均支持!

示例代码:html文件:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>sever sent event</title>
</head>
<body>
    <p>sever sent event informations</p>
    <p id="test"></p>
    <script>
        // 判断浏览器是否支持EventSource
        if(typeof(EventSource)!==undefined){
            // 创建EventSource对象
            var source=new EventSource("test.php");
            // 事件监听
            source.onmessage=function(event){
                document.getElementById(&#39;test&#39;).innerHTML+=event.data+"<br>";
            };
        }else{
            document.getElementById(&#39;test&#39;).innerHTML="sorry,浏览器不支持server sent event";
        }
    </script>
</body>
</html>
Copy after login

test.php:


<?php
header(&#39;Content-Type:text/event-stream&#39;);
header(&#39;Cache-Control:no-cache&#39;);

$time=date(&#39;r&#39;);
echo "data:The server time is: {$time} \n\n";
// 刷新输出数据
flush();
Copy after login

注意:后面没有内容,php文件可以不用"?>"关闭!

HTML5 WebSocket:

  1. WebSocket是HTML5提供的一种在单个TCP连接上建立全双工(类似电话)通讯的协议;

  2. 浏览器和服务器之间只需要进行一次握手的操作,浏览器和服务器之间就形成了一条快速通道,两者之间就可直接进行数据传送;

  3. 浏览器通过javascript建立WebSocket连接请求,通过send()向服务器发送数据,onmessage()接收服务器返回的数据。

 WebSocket如何兼容低浏览器:

  1. Adobe Flash Socket;

  2. ActiveX HTMLFile(IE);

  3. 基于multipart编码发送XHR;

  4. 基于长轮询的XHR

WebSocket可以用在多个标签页之间的通信!

相关推荐:

Nginx的Web缓存服务与新浪网的开源NCACHE模块

Web缓存杂谈_html/css_WEB-ITnose

基于反向代理的Web缓存加速可缓存的CMS系统设计_PHP

The above is the detailed content of HTML5 web caching and application caching. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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