Detailed explanation of H5

(1 Introduction

HTML5 is the latest HTML standard with new semantic, graphical and multimedia elements

【Advantage】

① Provides new elements and new APIs to simplify the construction of web applications;

② Cross-platform, designed to run on different types of hardware (PC, tablet, mobile phone, TV, etc.)

【Notice】

①The default character encoding of H5 is UTF-8;

【New Features】

Some of the most interesting new features of HTML5:

①New semantic elements, such as <header>, <footer>, <article>, and <section>;

② New form controls, such as numbers, dates, times, calendars and sliders;

③ Powerful image support (via <canvas> and <svg>);

④Powerful multimedia support (via <video> and <audio>);

⑤ Powerful new APIs, such as replacing cookies with local storage

[H5 deleted elements]

The following HTML 4.01 elements have been removed from HTML5:

<acronym>,<applet>,<basefont>,<big>,<center>,<dir>,<font>,<frame>,<frameset>,<noframes>,<strike>,<tt>

(2) Browser support

【Browser Support】

All modern browsers support HTML5. Additionally, all browsers, old and new, automatically treat unrecognized elements as inline elements. Because of this, can help older browsers deal with "unknown" HTML elements

[Define HTML5 elements as block-level elements]

HTML5 defines eight new semantic HTML elements. All are block-level elements.

The CSS display property can be set to block to ensure correct behavior in older browsers:

header, section, footer, aside, nav, main, article, figure {
    display: block;
}

 【向 HTML 添加新元素】

可以通过浏览器 trick 向 HTML 添加任何新元素:

本例向 HTML 添加了一个名为 <myHero> 的新元素,并为其定义 display 样式:

<script>document.createElement("myHero")</script>
  <style>
  myHero {
    display: block;
    background-color: #ddd;
    padding: 50px;
    font-size: 30px;
  } 
  </style> 
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<myHero>My First Hero</myHero>

 兼容:已添加的 JavaScript 语句 document.createElement("myHero"),仅适用于 IE

【Internet Explorer 的问题】

上述方案可用于所有新的 HTML5 元素,但是:

注意:Internet Explorer 8 以及更早的版本,不允许对未知元素添加样式。

幸运的是,Sjoerd Visscher 创造了 "HTML5 Enabling JavaScript", "the shiv":

<!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

 以上代码是一段注释,但是 IE9 的早期版本会读取它(并理解它)

【完整的 Shiv 解决方案】

引用 shiv 代码的链接必须位于 <head> 元素中,因为 Internet Explorer 需要在读取之前认识所有新元素

<!DOCTYPE html>
<html>
<head>
  <title>Styling HTML5</title>
  <!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
</head>
<body>
<h1>My First Article</h1>
<article>
London is the capital city of England. 
It is the most populous city in the United Kingdom, 
with a metropolitan area of over 13 million inhabitants.
</article>
</body>
</html>

 

(2)H5语义元素:

【什么是语义元素?】

语义元素清楚地向浏览器和开发者描述其意义。

非语义元素的例子:<div> 和 <span> - 无法提供关于其内容的信息。

语义元素的例子:<form>、<table> 以及 <img> - 清晰地定义其内容。

【H5新的语义元素】

H5 提供了定义页面不同部分的新语义元素:

<article> defines the article, <aside> defines content other than the page content, <details> defines additional details that the user can view or hide, <figcaption> defines the title of the <figure> element, and <figure> defines self-contained content, such as a figure representations, diagrams, photos, code listings, <footer> defines the document or section footer, <header> specifies the document or section header, <main> specifies the main content of the document,

<mark> defines important or emphasized text, <nav> defines navigation links, <section> defines sections in the document,

<summary> defines the visible title of the <details> element, <time> defines the date/time

 

 

(3) H5 migration:

Migrating from HTML4 to HTML5 The same techniques can be used to migrate from HTML4 and XHTML to HTML5.

<div id="header"> <header>
<div id="menu"> <nav>
<div id="content"> <section>
<div id="post"> <article>
<div id="footer"> <footer>

①【Modify document type】

From HTML4 doctype:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

Modified to HTML5 doctype:

<!DOCTYPE html>
 ②【Modify H5 encoded characters】

Modify the encoding information, from HTML4:

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

Change to HTML5:

<meta charset="utf-8">
 ③Add shiv

All modern browsers support HTML5 semantic elements.

Also, you can "teach" old browsers how to handle "unknown elements".

shiv added for Internet Explorer support:

<!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
④Change the <div> elements with id="header" and id="footer" to HTML5 <header> and <footer>

⑤ Change the <div> element with id="menu" to HTML5 <nav>

⑥ Change the <div> element with id="content" to HTML5 <section>

⑦ Change all <div> elements with class="post" to HTML5 <article>

【expand】

Html5shiv, referring to the Html5 tag structure

[Origin]

More and more sites are using HTML5 tags. But the situation is that there are still many people using IE6, IE7, IE8. In order to allow all website browsers to visit the website normally, Javascript is used to make browsers that do not support HTML5 support HTML tags. This is the way a lot of websites use it.

【solution】

There are the following two:

①为网站创建多套模板,通过程序对User-Agent的判断给不同的浏览器用户显示不同的页面,比如优酷网就是采用的这种模式;

②使用Javascript来使不支持HTML5的浏览器支持HTML标签,很多网站采用的这种方式。

   html5shiv主要解决HTML5提出的新的元素不被IE6-8识别,这些新元素不能作为父节点包裹子元素,并且不能应用CSS样式。让CSS 样式应用在未知元素上只需执行 document.createElement(elementName) 即可实现。html5shiv就是根据这个原理创建的。

   html5shiv的使用非常的简单,考虑到IE9是支持html5的,所以只需要在页面head中添加如下代码即可:

<!--[if lt IE 9]>
<script type="text/javascript" src="js/html5shiv.js"></script>
<![endif]-->
 

 

 

(4)H5代码规范

①【必需的属性】

请始终对图像使用 alt 属性。当图像无法显示时该属性很重要

<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">

请始终定义图像尺寸。这样做会减少闪烁,因为浏览器会在图像加载之前为图像预留空间

<img src="html5.gif" alt="HTML5" style="width:128px;height:128px">

②【避免长代码行】

当使用 HTML 编辑器时,通过左右滚动来阅读 HTML 代码很不方便。

请尽量避免代码行超过 80 个字符

③【不推荐省略 <html> 和 <body> 标签】

对于可访问应用程序(屏幕阅读器)和搜索引擎,声明语言很重要

省略 <html> 或 <body> c可令 DOM 和 XML 软件崩溃;省略 <body> 会在老式浏览器(IE9)中产生错误

④【HTML 注释】

短注释应该在单行中书写,并在 <!-- 之后增加一个空格,在 <!-- 之前增加一个空格:

<!-- This is a comment -->

长注释,跨越多行,应该通过 <!-- 和 --> 在独立的行中书写:

<!-- 
  This is a long comment example. This is a long comment example. 
  This is a long comment example.
  This is a long comment example. This is a long comment example. 
  This is a long comment example.
-->

长注释更易观察,如果它们被缩进两个空格的话

⑤【使用小写文件名】

一 . 大多数 web 服务器(Apache、Unix)对文件名的大小写敏感:

不能以 london.jpg 访问 London.jpg

二 . 其他 web 服务器(微软,IIS)对大小写不敏感:

能够以 london.jpg 或 London.jpg 访问 London.jpg

     如果从对大小写不敏感的服务器转到一台对大小写敏感的服务器上,这些小错误将破坏网站

     为了避免这些问题,请始终使用小写文件名(如果可以的话)

关于文件名小写,网上有许多说法,具体查询后总结如下:

           ①可移植性:使用小写文件名Linux 系统是大小写敏感的,而 Windows 系统和 Mac 系统正好相反,大小写不敏感。一般来说,这不是大问题。但是,如果两个文件名只有大小写不同,其他都相同,跨平台就会出问题

          ②易读性:小写文件名通常比大写文件名更易读,比如accessibility.txt比ACCESSIBILITY.TXT易读

          ③易用性:某些系统会生成一些预置的用户目录,采用首字母大写的目录名。比如,Ubuntu 在用户主目录会默认生成Downloads、 Pictures、Documents等目录。所以,用户的文件都采用小写文件名,就很方便与上面这些目录或文件相区分。

           为什么操作系统会采用这样的大写文件名?

原因也很简单,因为早期 Unix 系统上,ls命令先列出大写字母,再列出小写字母,大写的路径会排在前面。因此,如果目录名或文件名是大写的,就比较容易被用户首先看到

           

 

(5)H5图形

一 . 画布canvas,我在之前文章里做了总结

二 . SVG

H5 支持内联 SVG,SVG 指可伸缩矢量图形 ,定义用于网络的基于矢量的图形,在放大或改变尺寸的情况下其图形质量不会有损失

具体我在后面文章http://570109268.iteye.com/blog/2409710里做了总结

 

(6)HTML多媒体

Web 上的多媒体指的是音效、音乐、视频和动画

【什么是多媒体?】

多媒体来自多种不同的格式,它可以是您听到或看到的任何内容,文字、图片、音乐、音效、录音、电影、动画等等。在因特网上,经常发现嵌入网页中的多媒体元素,现代浏览器已支持多种多媒体格式。接下来介绍不同的多媒体格式,以及如何在您的网页中使用它们

【浏览器支持】

第一款因特网浏览器只支持文本,而且即使是对文本的支持也仅限于单一字体和单一颜色。随后诞生了支持颜色、字体和文本样式的浏览器,图片支持也被加入

不同的浏览器以不同的方式处理对音效、动画和视频的支持。某些元素能够以内联的方式处理,而某些则需要额外的插件

【多媒体格式】

多媒体元素(比如视频和音频)存储于媒体文件中

确定媒体类型的最常用的方法是查看文件扩展名。当浏览器得到文件扩展名 .htm 或 .html 时,它会假定该文件是 HTML 页面。.xml 扩展名指示 XML 文件,而 .css 扩展名指示样式表。图片格式则通过 .gif 或 .jpg 来识别。多媒体元素元素也拥有带有不同扩展名的文件格式,比如 .swf、.wmv、.mp3 以及 .mp4

【HTML插件】

 <object> 的作用是支持 HTML 助手(插件)

辅助应用程序也称为插件,可用于播放音频和视频(以及其他)

辅助程序是使用 <object> 标签来加载的

One advantage of using helper programs to play video and audio: allows the user to control some or all of the playback settings, most helper applications allow manual (or programmatic) volume settings and playback functions (such as rewind, pause, stop, and play). control

 

1. HTML Audio

①Problems and solutions:

Playing audio in HTML is not easy and requires a lot of tricks to make sure that audio files work in all browsers (Internet Explorer, Chrome, Firefox, Safari, Opera) and on all hardware (PC, Mac , iPad, iPhone) play

②Using a plug-in

A browser plug-in is a small computer program that extends the standard functionality of a browser

Plugins can be used for many purposes: play music, display maps, verify bank accounts, control input, and more

Plugins can be added to HTML pages using the <object> or <embed> tags

These tags define containers for resources (usually non-HTML resources) that, depending on the type, are displayed either by the browser or by external plugins

【HTML 4.01 Multimedia Tag】

label description
<applet> Disapprove. Defines an inline applet.
<embed> Deprecated in HTML4, allowed in HTML5. Define an inline object.
<object> Define an inline object.
<param> Define the parameters of the object.

【HTML 5 Multimedia Tag】

label description
<audio> Tags define sounds, such as music or other audio streams.
<embed> Tags define embedded content, such as plugins.

【Insert audio】

  1. The <embed> element

The <embed> tag defines a container for external (non-HTML) content (this is an HTML5 tag, illegal in HTML4, but valid in all browsers)

<embed height="100" width="100" src="http://www.w3school.com.cn/i/horse.mp3"></embed>
<p><b>Note:</b> The browser may require a plug-in to play the file. </p>
 question:

① The <embed> tag is invalid in HTML 4, and the page cannot pass HTML 4 validation;

② Different browsers support different audio formats;

③ If the browser does not support the file format, the audio cannot be played without a plug-in; if the user does not install the plug-in, the audio cannot be played;

④If the file is converted to other formats, it still cannot be played in all browsers

[Note]: Use <!DOCTYPE html> (HTML5) to solve validation problems

 2. <object> element

The <object tag> tag can also define a container for external (non-HTML) content

<object height="100" width="100" data="song.mp3"></object>
 The problem is the same as the <embed> tag

 3. The <audio> element

HTML5 element, illegal in HTML 4, but valid in all browsers

<audio controls="controls">
  <source src="http://www.w3school.com.cn/song.mp3" type="audio/mp3" />
  <source src="http://www.w3school.com.cn/song.ogg" type="audio/ogg" />
Your browser does not support this audio format.
</audio>
 The above example uses an mp3 file so that it is valid in Internet Explorer, Chrome and Safari

To make the audio work in Firefox and Opera as well, an ogg type of file is added. If it fails, an error message is displayed

question:

① The <audio> tag is invalid in HTML 4, and the page cannot pass HTML 4 validation;

②The audio file must be converted to a different format;

③ The <audio> element does not work in older browsers

[Note]: Use <!DOCTYPE html> (HTML5) to solve validation problems

 4. The easiest way to add audio

Using Yahoo Media Player is a different approach, simply let Yahoo do the work of playing the song

It can play mp3 and a range of other formats, and with a simple line of code, it can be added to web pages, easily turning HTML pages into professional playlists

【Yahoo Media Player】

<a href="http://www.w3school.com.cn/song.mp3">Play Sound</a>
<!--It is free to use Yahoo Player, if you want to use it, you need to insert this JS into the bottom of the page-->
<!--Then simply link the MP3 file into the HTML and JS will automatically create a play button for each song-->
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js">
</script>

Yahoo Media Player provides users with a small play button instead of a full player. However, when the button is clicked, the full player pops up.

Note: The player is always docked at the bottom of the window frame. Just click on it to slide it out

 5. Use hyperlinks

If a web page contains a hyperlink to a media file, most browsers use a "helper application" to play the file.

以下代码片段显示指向 mp3 文件的链接。如果用户点击该链接,浏览器会启动“辅助应用程序”来播放该文件:

<a href="http://www.w3school.com.cn/song.mp3">Play the sound</a>

 

 二 . HTML视频

 在 HTML 中播放视频的方法有很多种,但并不容易。需要谙熟大量技巧,以确保视频文件在所有浏览器中(Internet Explorer, Chrome, Firefox, Safari, Opera)和所有硬件上(PC, Mac , iPad, iPhone)都能够播放。

  1. <embed> 标签

<embed width="320" height="240" src="http://www.w3school.com.cn/i/bookmark.swf" />

  2. <object> 标签

   <object> 标签的作用是在 HTML 页面中嵌入多媒体元素

<object data="http://www.w3school.com.cn/movie.swf" height="200" width="200"/>

【问题】

①如果浏览器不支持 Flash,将无法播放视频;

②iPad 和 iPhone 不能显示 Flash 视频;

③如果将视频转换为其他格式,那么它仍然不能在所有浏览器中播放

 3 .<video> 标签

HTML 5 中的新标签,作用是在 HTML 页面中嵌入视频元素

以下 HTML 片段会显示一段嵌入网页的 ogg、mp4 或 webm 格式的视频:

<video width="320" height="240" controls="controls">
  <source src="http://www.w3school.com.cn/movie.mp4" type="video/mp4" />
  <source src="http://www.w3school.com.cn/movie.ogg" type="video/ogg" />
  <source src="http://www.w3school.com.cn/movie.webm" type="video/webm" />
Your browser does not support the video tag.(浏览器不支持)
</video>

【问题】

①必须把视频转换为很多不同的格式;

②<video> 元素在老式浏览器中无效;

③<video> 元素无法通过 HTML 4 和 XHTML 验证

 4.HTML 添加视频最好方法

 HTML 5 + <object> + <embed>

<video width="320" height="240" controls="controls">
  <source src="movie.mp4" type="video/mp4" />
  <source src="movie.ogg" type="video/ogg" />
  <source src="movie.webm" type="video/webm" />
  <object data="movie.mp4" width="320" height="240">
    <embed src="movie.swf" width="320" height="240" />
  </object>
</video>

 上例中使用了 4 中不同的视频格式。HTML 5 <video> 元素会尝试播放以 mp4、ogg 或 webm 格式中的一种来播放视频。如果均失败,则回退到 <embed> 元素。

【问题】

①必须把视频转换为很多不同的格式

②<video> 元素无法通过 HTML 4 和 XHTML 验证;

③<embed> 元素无法通过 HTML 4 和 XHTML 验证

注释:使用 <!DOCTYPE html> (HTML5) 解决验证问题

 5 . 优酷解决方案

在 HTML 中显示视频的最简单的方法是使用优酷等视频网站

如果希望在网页播放视频,可以把视频上传到优酷视频网站,然后在网页中插入 HTML 代码即可播放视频:

<embed src="http://player.youku.com/player.php/sid/XMzI2NTc4NTMy/v.swf" 
width="480" height="400" 
type="application/x-shockwave-flash">
</embed>

  6 . 使用超链接

如果网页包含指向媒体文件的超链接,大多数浏览器会使用“辅助应用程序”来播放文件

以下代码片段显示指向 AVI 文件的链接。如果用户点击该链接,浏览器会启动“辅助应用程序”,比如 Windows Media Player(Windows媒体播放器)来播放这个 AVI 文件:

<a href="http://www.w3school.com.cn/movie.swf">Play a video file</a>

 

 

(7)H5的API

①地理位置

HTML5 Geolocation(地理位置)API 用于获得用户的地理位置

鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的

【兼容】

IE9、Firefox、Chrome、Safari 以及 Opera 支持地理定位

注释:对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确

 使用 getCurrentPosition() 方法来获得用户的位置,下例是一个简单的地理定位实例,可返回用户位置的经度和纬度

②拖放

拖放(Drag 和 Drop)是很常见的特性,它指的是您抓取某物并拖入不同的位置

拖放是 HTML5 标准的组成部分:任何元素都是可拖放的

具体我在前面文章http://570109268.iteye.com/admin/blogs/2408954里做过总结

 

 

(8)H5本地存储

具体我在后面文章http://570109268.iteye.com/admin/blogs/2409845里做了总结

HTML5本地存储:优于 cookies

【什么是 HTML 本地存储?】

通过本地存储(Local Storage),web 应用程序能够在用户浏览器中对数据进行本地的存储。

在 HTML5 之前,应用程序数据只能存储在 cookie 中,包括每个服务器请求。本地存储则更安全,并且可在不影响网站性能的前提下将大量数据存储于本地。

与 cookie 不同,存储限制要大得多(至少5MB),并且信息不会被传输到服务器。

本地存储经由起源地(origin)(经由域和协议)。所有页面,从起源地,能够存储和访问相同的数据。

【HTML 本地存储对象】

HTML 本地存储提供了两个在客户端存储数据的对象:

 ① window.localStorage - 存储没有截止日期的数据

 ② window.sessionStorage - 针对一个 session 来存储数据(当关闭浏览器标签页时数据会丢失)

在使用本地存储时,请检测 localStorage 和 sessionStorage 的浏览器支持:

if (typeof(Storage) !== "undefined") {
    // 针对 localStorage/sessionStorage 的代码
    alert("支持H5本地缓存")
} else {
    // 抱歉!不支持 Web Storage ..
    alert("不支持H5本地缓存")
}

 

 

(9)H5应用程序缓存

使用应用程序缓存,通过创建 cache manifest(缓存清单)文件,可轻松创建 web 应用的离线版本

①【什么是应用程序缓存?】

HTML5 引入了应用程序缓存(Application Cache),这意味着可对 web 应用进行缓存,并可在没有因特网连接时进行访问。

通俗理解就是离线缓存,可在无网络状态下访问

②【优势】

应用程序缓存为应用带来三个优势:

 1.离线浏览 - 用户可在应用离线时使用它们;

 2.速度 - 已缓存资源加载得更快;

 3.减少服务器负载 - 浏览器将只从服务器下载更新过或更改过的资源

③【兼容】

IE10及其他主流浏览器均支持

④【Cache Manifest (缓存清单)基础】

 如需启用应用程序缓存,请在文档的 <html> 标签中包含 manifest 属性:

<!DOCTYPE HTML>
<html manifest="demo.appcache">
...
</html>

每个指定了 manifest 的页面在用户对其访问时都会被缓存。如果未指定 manifest 属性,则页面不会被缓存(除非在 manifest 文件中直接指定了该页面)

manifest 文件的建议文件扩展名是:".appcache"

【注意:】manifest 文件需要设置正确的MIME-type,即text/cache-manifest,必须在web服务器上进行配置

⑤【Manifest(清单) 文件】

manifest 文件是简单的文本文件,它告知浏览器被缓存的内容(以及不缓存的内容)

由三部分组成:

 1 . CACHE MANIFEST(缓存清单) - 在此标题下列出的文件将在首次下载后进行缓存

 2 . NETWORK (网络)- 在此标题下列出的文件需要与服务器的连接,且不会被缓存

 3 . FALLBACK (回退)- 在此标题下列出的文件规定当页面无法访问时的回退页面(比如 404 页面)

下面分开讲解:

 1 . CACHE MANIFEST(缓存清单)

第一行,CACHE MANIFEST,是必需的:

CACHE MANIFEST
/theme.css
/logo.gif
/main.js

上面的 manifest 文件列出了三个资源:一个 CSS 文件,一个 GIF 图像,以及一个 JavaScript 文件

当 manifest 文件被加载后,浏览器会从网站的根目录下载这三个文件;然后,无论用户何时与因特网断开连接,这些资源依然可用

 2 . NETWORK(网络)

下面的 NETWORK 部分规定文件 "login.php" 永远不会被缓存,且离线时是不可用的:

NETWORK:
login.asp

可以使用星号来指示所有其他其他资源/文件都需要因特网连接:

NETWORK:
*

 3 . FALLBACK(回退)

规定如果无法建立因特网连接,则用 "offline.html" 替代 /html/ 目录中的所有文件:

FALLBACK:
/html/ /offline.html

注释:第一个 URI 是资源,第二个是替补

 ⑥ 【更新缓存

一旦应用被缓存,它就会保持缓存直到发生下列情况:

  1 . 用户清空浏览器缓存;

  2 . manifest 文件被修改(参阅下面的提示);

  3 . 由程序来更新应用缓存

更新注释行中的日期和版本号是一种使浏览器重新缓存文件的办法

一旦文件被缓存,则浏览器会继续展示已缓存的版本,即使您修改了服务器上的文件。为了确保浏览器更新缓存,您需要更新 manifest 文件

注释:浏览器对缓存数据的容量限制可能不太一样(某些浏览器的限制是每个站点 5MB)

 ⑦【完整的 Cache Manifest 文件】

CACHE MANIFEST
# 2012-02-21 v1.0.0
/theme.css
/logo.gif
/main.js

NETWORK:
login.asp

FALLBACK:
/html/ /offline.html

 

【提示:】

 1 . 以 "#" 开头的是注释行,但也可满足其他用途

 2 . 应用的缓存只会在其 manifest 文件改变时被更新

 3 . 如果编辑了一幅图像,或者修改了一个 JavaScript 函数,这些改变都不会被重新缓存

 4 . 更新注释行中的日期和版本号是一种使浏览器重新缓存文件的办法

 

 

(10)Web Workers

 Web worker 是运行在后台的 JavaScript,不会影响页面的性能。

【什么是 Web Worker?】

当在 HTML 页面中执行脚本时,页面是不可响应的,直到脚本已完成。

Web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 运行在后台。

【兼容】

IE10及其他主流浏览器均兼容

【检测 Web Worker 支持】

在创建 web worker 之前,请检测用户浏览器是否支持它:

<script>
    window.onload = function demo(){
        if (typeof(Worker) !== "undefined") {
            alert("支持Web worker")
        } else {
            alert("不支持Web Worker!")
        }
    }
</script>

 【创建 Web Worker 文件】

现在,先在一个外部 JavaScript 文件中创建web worker

在此处,我们创建了计数脚本,该脚本存储于 "demo_workers.js" 文件中:

var i = 0;
function timedCount() {
    i = i + 1;
    postMessage(i);
    //console.log(documnet);因为是外部JS,所以无法获取文档相关属性
    setTimeout("timedCount()",500);
}
timedCount();

   以上代码中重要的部分是 postMessage() 方法 - 它用于向 HTML 页面传回一段消息

   注释: web worker 通常不用于如此简单的脚本,而是用于更耗费 CPU 资源的任务

【创建 Web Worker 对象】

现在已经有了 web worker 文件,需要从 HTML 页面调用它

下面的代码行检测是否存在 worker,如果不存在,- 它会创建一个新的 web worker 对象,然后运行 "demo_workers.js" 中的代码:

if (typeof(w) == "undefined") {
    w = new Worker("demo_workers.js");
}

然后我们就可以从 web worker 发生和接收消息了

向 web worker 添加一个 "onmessage" 事件监听器:

w.onmessage = function(event){
    document.getElementById("result").innerHTML = event.data;
};

当 web worker 传送消息时,会执行事件监听器中的代码;来自 web worker 的数据会存储于 event.data 中

【终止 Web Worker】

当创建 web worker 后,它会继续监听消息(即使在外部脚本完成后)直到其被终止为止

如需终止 web worker,并释放浏览器/计算机资源,请使用 terminate() 方法:

w.terminate();

【复用 Web Worker】

如果把 worker 变量设置为 undefined,在其被终止后,可以重复使用该代码:

w = undefined;

 【总结】

Web Worker 和 DOM,由于 web worker 位于外部文件中,它们无法访问下例 JavaScript 对象:

window 对象,document 对象,parent 对象

 

 

(11)H5的SSE

HTML Server-Sent(服务器) 事件

 【检测 Server-Sent 事件支持】

以下编写了一段额外的代码来检测服务器发送事件的浏览器支持:

if(typeof(EventSource) !== "undefined") {
    // 是的!支持服务器发送事件!
    // 一些代码.....
} else {
    // 抱歉!不支持服务器发送事件!
}

【EventSource 对象】

我们可以使用 onmessage 事件来获取消息,不过还可以使用其他事件:

事件                                    描述

onopen           当通往服务器的连接被打开

onmessage             当接收到消息

onerror                        当发生错误

 

 

 

 

 

 

 

 

 

 

 

 

 

.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326153127&siteId=291194637