Home>Article>Web Front-end> HTML5 new features: offline caching technology-php Chinese website
1. The cause of offline caching.
Web pages before HTML5 are all connectionless and must be connected to the Internet to access. This is actually a feature of the web. In fact, this is not a big problem for the PC era, but in the mobile Internet era,
The location of the device terminal is no longer fixed and relies on wireless signals, which reduces the reliability of the network. For example, if you are sitting on a train and pass through a tunnel (15 minutes), you will not be able to access the website, which is very inconvenient.
The offline web application allows us to interact with the website when offline.
2. What is an offline web application? Why develop offline web applications?
Offline web application refers to: when the client does not establish a connection with the web application server locally, the web application can be used locally on the client to perform related operations.
Web applications have become more and more complex, and many fields are utilizing Web applications. However, it has a fatal flaw: if the user does not have a connection to the Internet, he
cannot use this web application. Therefore, H5 has added a new API, which uses a local caching mechanism to solve this problem and makes the development of offline applications possible.
If you want the web application to work normally when offline, you must put all the resource files that make up the web application, such as HTML files, CSS files, and JavaScript scripts
files When the server does not establish a connection with the Internet, the resource files in the local cache can also be used to run the web application normally.
3. What is local cache and the difference between local cache and browser web page cache.
There are obvious differences in many aspects between the local cache of web applications and the web page cache of browsers.
1. The local cache serves the entire web application, while the browser's web page cache only serves a single web page. Any web page has a web cache. The local cache caches the pages specified by the cache
.
2. Web page caching is unsafe and unreliable because we don’t know which web pages are cached in the website and which resources on the web page are cached. The local cache is reliable. We can control which content is cached and which content is not cached. Developers can also use programming methods to control cache updates and use cache objects to Various properties, states and events to develop more powerful offline
applications.
3. (Some) browsers will actively save their own cache files to speed up website loading. However, to implement browser caching, a prerequisite must be met, that is, the network must maintain a connection
. If the network is not connected,
Even if the browser enables caching of a site, it still cannot open the site. You will only receive an error message. With offline web applications, we can actively tell the browser which files should be obtained or cached from the website server, and the website can still be accessed when the network is offline.
4. How to implement HTML5 application caching? What is a manifest file? What content specified in the file needs to be cached locally, and what content does not need to be cached locally?
Implementing HTML5 application caching is very simple, requires only three steps, and does not require any API. You only need to tell the browser which files need to be cached offline, and make some
simple settings on the server and web pages to achieve it.
4-1. Create a cache.manifest file and ensure that the file has the correct content.
4-2. Set the content type on the server.
4-3. All HTML files point to cache.manifest.
Specific implementation:
4-1: First, we create a file named cache.manifest. Just use Notepad on the Windows platform (other IDEs can also be used). The content of the file is as follows:
Notes:1. The first line must be the text "CACHE DMANIFEST" to save this file. The function of the file informs the browser, that is, specific settings are made for the resource files in the local cache.
2. In the manifest file, you can add comments to provide some necessary explanations or explanations. Comment lines start with "#" characters.
3. The part after CACHE lists the files we need to cache.
4. Specify two resource files in each line after FALLBACK. The first resource file is a resource file that can be used when accessed online, and the second resource file is
which cannot be used. Alternate resource file used when accessing online.
5. After NETWORK, you can specify an online whitelist, that is, list the files that we do not want to store offline, because usually their contents require Internet access to be meaningful.
In addition, we can use shortcuts in this part: wildcard *. This will tell the browser that the application server is fetching any files or URLs that are not mentioned in the display section.
4-2: Set the content type on the server.
When you actually run or test an offline web application, you need to configure the server so that the server supports the text/cache-manifest MIME type (specified in h5
The MIME type of the manifest file is text/cache-manifest). For example, when configuring the Apache server, you need to find the file (.htaccess)
{apache_home}/conf/mime.type, and add the following code at the end of the file:
text /cache-manifest .manifest . The steps in Microsoft's IIS server are as follows:
(1). Right-click to select the default website or the website that needs to be added, and the properties dialog box will pop up
(2). Select "http Header" tag
(3). Under MIME mapping, click the File Type button
(4). In the opened MIME type dialog box, click the New button
(5). Enter "manifest" in the associated extension text, enter "text/cache-manifest" in the content type text box, and then click the OK button.
4-3: Set the direction of the HTML file.
87a8930f5327cd917e3ebb2ece0087e8
After completing this step, all steps of web offline caching are completed. Web pages will now open much faster (even when online) because the content of browsed files has not changed and is stored locally.
Notes:
1. Each HTML page of the website must set the manifest attribute of the HTML element. Must to do;
2. In your entire website application, there can only be one cache.manifest file (it is recommended to place it in the root directory of the website);
3. Some browsers ( For example, IE8-) does not support HTML5 offline caching;
4, comment lines starting with "#" can serve other purposes. The application's cache is updated when its manifest file changes. If you edit an image, or modify a JavaScript function,
these changes will not be re-cached. Updating the date and version number in the comment line is a way to cause the browser to re-cache the file.
5. Master the applicationCache object and its properties and events for local caching:
(1) Cache update:
When a web application is loaded from the cache At this time, all related files are also obtained directly from the cache. When online, the browser asynchronously checks whether the manifest file has been updated.
If there is an update, the new manifest file and all files listed in the manifest will be downloaded and re-saved to the program cache. But please note that the browser only checks the manifest file and does not
check whether the cached file has been updated. If you modify a cached js file and want the file to take effect, you must update the manifest file. . Since the file column
table that the application depends on has not actually changed, the easiest way is to update the version.
The code is as follows:
CHCHE MANIFEST CACHE: #version2 (更改这个数字以便让浏览器重新下载) myapp.html myapp.css myapp.js
Note:
① The operations of the browser checking the manifest file and updating the cache are asynchronous. They may be before loading the application from the cache, or they may be performed at the same time. Therefore, for a simple web application
, after updating the manifest file, the user must load the application twice to ensure that the latest version takes effect: the first time is to load the old version from the cache and then update the cache; The second time is to load the latest version from the
cache.
②. The browser will trigger a series of events during the cache update process. You can track this process by registering a handler and provide feedback to the user.
The code is as follows:
applicationCache.onupdateready= function(){ var reload = confirm(“A new version of this application is available\n and will be used the next time you reload.\n”); if(reload) location.reload(); }
This event is registered on the ApplicationCache object, which is the value of the applicationCache attribute of the window. Browsers that support application caching define this attribute.
(2) Handling application cache-related events:
//下面所有的事件处理程序都使用此函数来显示状态消息 //由于都是通过调用status函数来显示状态,因此所有处理程序都返回false来阻止浏览器显示其默认状态消息 function status(msg){ doucment.getElementById(“statusline”).innerHTML= msg; console.log(msg); //同时在控制台输出此消息,便于调试 } //每当应用程序载入的时候,都会检查该清单文件 //也总会首先触发“checking”事件 window.applicationCache.onchecking = function(){ status(“checking for a new version.”); return false; } //如果没有改动,同时应用程序也已经缓存了 //”noupdate”事件被触发,整个过程结束 window.applicationCache.onnoupdate = function(){ } //如果还未缓存应用程序,或者清单文件有改动 //那么浏览器会下载并缓存清单中的所有资源 //触发”downloading”事件,同时意味着下载过程开始 window.applicationCache.ondownloading = function(){ status(“Downloading new version”); window.progresscount = 0; return false; } //在下载过程中会间断性触发“progress“事件 //通常是在每个文件下载完毕的时候 window.applicationCache.onprogress = function(e){ varprogress = “”; if(e && e.lengthComputable) progress = “ ”+Math.round(100*e.loaded/e.total)+”%” else progress = “(“+(++progresscount)+”)” return false; } //当下载完成并且首次将应用程序下载到缓存中时,浏览器会触发“cached“事件 window.applicationCache.oncached = function(e){ status(“Thisapplication is now cached locally”); return false; } //当下载完成并将缓存中的应用程序更新后,浏览器会触发”updaterady”事件 //要注意的是:触发此事件的时候,用户任然可以看到老版本的应用程序 window.applicationCache.onupdateready = function(e){ status(“Anew version has been downloaded. Reload to run it”); return false; } //如果浏览器处于离线状态,检查清单列表失败,则会触发“error“事件 //当一个未缓存的应用程序引用一个不存在的清单文件,也会触发此事件 window.applicationCache.onerror = function(e){ status(“Couldn’tload manifest or cache application”); return false; } //如果一个缓存的应用程序引用一个不存在的清单文件,会触发“obsolete“ //同时将应用从缓存中移除之后不会从缓存而是通过网络加载资源 window.applicationCache.onobsolete = function(e){ status(“Thisapplication is no longer cached. Reload to get the latest version from thenetwork.”); return false; }
Every time an html file with a manifest attribute is loaded, the browser will trigger the "checking" event. And load the manifest file through the network. But later, different events will be triggered according to
different situations.
Event list:
(1).No update available
If the application has been cached and the manifest file has not been moved, the browser will trigger the noupdate event
(2). Updates available
If the application has been cached and the manifest element has been changed, the browser will trigger the downloading event and start downloading and caching all resources listed in the manifest file.
As the download process progresses, the browser will also trigger the "progress" event. After the download is completed, the "updateready" event will be triggered.
(3). Loading a new application for the first time
If the application has not been cached, the downloading and progress events will be triggered as mentioned above. However, when the download is completed, the browser will trigger the "cached" event
instead of the updateready event
(4). The browser is offline
If the browser is Offline, it cannot check the manifest file and it fires the "error" event.
If an uncached application references a manifest file that does not exist, the browser will also trigger this event
(5).The manifest file does not exist
If browsing The browser handles the online status and the application has been cached, but the manifest file does not exist. The browser will trigger the obsolete event and remove the application from the cache.
Cache status:缓存的状态可以通过window.applicationCache.status获得,其状态主要包括如下6种:
const unsigned short UNCACHED=0;//未缓存(应用程序没有设置manifest属性:未缓存) const unsigned short IDLE=1;//空闲状态(清单文件已经检查完毕,并且已经缓存了最新的应用程序) const unsigned short CHECKING=2;//检查中(浏览器正在检查清单文件) const unsigned short DOWNLOADING=3;//下载中(浏览器正在下载并缓存清单中列举的所有文件) const unsigned short UPDATEREADY=4;//更新准备中(已经下载和缓存了最新版的应用程序) const unsigned short OBSOLETE =5;//过期状态(清单文件不存在,缓存将被清除) readonly attribute unsigned short status;
六、ApplicationCache对象还定义了两个方法update()和swapCache():
(1).update
显式调用了更新缓存算法以检测是否有最新版本的的应用程序。这导致浏览器检测同一个清单文件(并触发相同的事件),
这和第一次载入应用程序时的效果是一样的。
(2).swapCache
它告诉浏览器可以弃用老缓存,所有的请求都从新缓存中获取。注意,这并不会重新载入应用程序:所有已经载入的html文件
、图片、脚本等资源都不会改变。但是,之后的请求将从最新的缓存中获取。这会导致“版本错乱”的问题,因此一般不推荐使用
,除非应用程序设计得很好,确保这样的方式没有问题。只有ApplicationCache.UPDATEREADY和
ApplicationCache.ABSOLETE 时调用 swapCache()才有意义(当状态OBSOLETE时,调用它可以立即弃用废弃的缓存,
让之后所有的请求都通过网络获取)。如果状态属性是其他数值的时候调用swapCache()方法,它就会抛出异常。
七、如何判断在线还是离线状态?
离线web应用指的是将自己“安装”在应用程序缓存中的程序,使得哪怕在浏览器处于离线状态时依然可访问它。为了在离线状态可用,
Web应用需要可以告知别人自己是离线还是在线,同时当网络连接的状态发生改变时候也能“感知”到。通过navigator.onLine属性,
navigator.onLine是HTML5定义用来检测设备是在线还是离线。对应的值为false或true。但是不同浏览器表现并不一致。
IE 6+和Safari 5+能够正确的检测到网络已断开,并将navigator.onLine设为flase。
Firefox 3+和Opera 10.6+也支持navigator.onLine。但需要手动讲浏览器设置为脱机模式才能让浏览器正常工作。
Chrome 11及以上版本始终将navigator.onLine设为true。(不过作者的Chrome 21已经能正常使用了)
HTML5定义了online&offline事件用于监听网络状态变化。
window.addEventListener('online', callback);// 离线到上线
window.addEventListener('offline', callback);// 上线到离线
目前除了IE(IE只支持navigator.onLine属性)外,其他最新浏览器都支持这个事件。
八、离线Web应用实战。
通过一个简单的记事本程序——PermaNote,来解释如何使用。程序将用户的文本保存到localStorage中,并且在网络连接可用的时候,
将其上传到服务器,PermaNote只允许用户编辑单个笔记。
PermaNote应用包含3个文件,一个应用清单文件、一个html页面文件,一个实现逻辑的js文件。
Demo: http://xuanfengge.com/demo/201506/appcache/permanote.html
①.premanote.appcache部分:
CACHE MANIFEST # PermaNote v8 permanote.html permanote.js NETWORK: note
②.permanote.html部分:
PermaNote Editor
③.permanote.js部分
status()函数用于显示状态栏消息,save()函数将笔记本保存到服务器,sync()用于确保本地与服务器文本的同步。
应用程序的时间处理程序解释:
(1).onload
尝试和服务器同步,一旦有新版本的笔记并且完成同步后,就启用编辑器窗口。
save()和sync()函数发出HTTP请求,并在XMLHttpRequest对象上注册一个onload时间处理程序来获取上传或者
下载完成的提醒。
(2).onbeforeunload
在未上传前,把当前版本的笔记数据保存到服务器上。
(3).oninput
每当textarea输入框内容发生变化时,都将其内容保存到localStorage中,并启动一个计时器。当用户停止编辑超过5秒
,将自动把数据保存到服务器。
(4).onoffline
当浏览器进入离线状态时,在状态栏显示离线消息。
(5).ononline
当浏览器回到在线状态时,同步服务器,检查是否有新版本的数据,并且保存当前版本的数据。
(6).onupdateready
如果新版本的应用已缓存,则在状态栏展示消息告知用户。
(7).onnoupdate
如果应用程序缓存没有发生变化,则同时用户仍在运行当前版本。
The above is the detailed content of HTML5 new features: offline caching technology-php Chinese website. For more information, please follow other related articles on the PHP Chinese website!