Home > Backend Development > PHP Tutorial > HTML5 web cache and application cache (cookie, session)

HTML5 web cache and application cache (cookie, session)

韦小宝
Release: 2023-03-19 14:08:02
Original
1562 people have browsed it

This article mainly introduces HTML5 Web caching and application caching (cookie, session). The editor thinks it is quite good. Now I share it with you, including the HTML5 source code, and also for your reference. If you are interested in HTML5, please follow the editor to take a look.

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

##session:

Since HTTP is stateless, 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 can be seen 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:

    ##localStorage.setItem(key, value): Set (save) data; equivalent to localStorage.key=value!
  1. localStorage.getItem(key): Get data
  2. localStorage.removeItem (key): Delete a single data
  3. localStorage.clear(): Delete all data
  4. localStorage.key(index): Get a certain Index key value
  5. <!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
  6. Program running result:

##Note: The key-value pair is in string

If saved, the type should be changed according to requirements (for example, for addition, it should be changed to 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 application cache, you need to specify the manifest attribute (extension: .appcache); if the manifest attribute is not specified, the page will not be cached (unless it is in the manifest file This page is specified directly!)

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

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

Updating the 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是运行在后台的javascript,独立于其它脚本,不会影响页面性能!

而一般的HTML页面上执行脚本时,除非脚本加载完成,否则页面不会响应!

支持情况: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可以用在多个标签页之间的通信!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

相关推荐:

HTML5单页面手势滑屏切换如何实现

html5的页面结构需要注意那些方面

HTML5存储方式小结

The above is the detailed content of HTML5 web cache and application cache (cookie, session). 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