search
HomeWeb Front-endH5 TutorialHTML5 WebApp part4:使用 Web Workers 来加速您的移动 Web 应用程序(下) ...

清单 4. loadDeals 函数

var deals = [];
var sections = [];
var dealDetails = {};
var dealsUrl = "http://deals.ebay.com/feeds/xml";
function loadDeals(){
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
               var i = 0;
               var j = 0;
               var dealsXml = this.responseXML.firstChild;
               var childNode = {};
               for (i=0; i
<p>清单 4 展示了 <code>loadDeals</code> 函数,以及应用程序中使用的全局变量。您使用了一个 deals 数组和一个 sections 数组。它们是相关交易的附加组(例如,<code>Deals under $10</code>)。还有一个名为 <code>dealDetails</code> 的映射,其键是 Item IDs(来自于交易数据),其值是从 eBay Shopping <a title="API" href="http://www.31358.cn/api/">API</a> 获取的详细信息。 </p>
<p>您首先调用一个代理,该代理又将调用 eBay Daily Deals REST <a title="API" href="http://www.31358.cn/api/">API</a>。这将把交易列表作为一个 XML 文档提供给您。您解析用于进行 Ajax 调用的 XMLHttpRequest 对象的 <code>onreadystatechange</code> 函数中的文档。您还使用其他两个函数,<code>parseDeal</code> 和 <code>parseSection</code>,来将 XML 节点解析为更易于使用的 JavaScript 对象,但由于它们只是令人厌烦的 XML 解析函数,因此我在这里没有包括它们。最后,在解析了 XML 后,您还使用了另外两个函数,<code>createDealUi</code> 和 <code>createSectionUi</code>,来修改 DOM。此时,这个 UI 如 图 1 所示。 </p>
<p><a href="http://www.31358.cn/wp-content/uploads/2011/12/image0012.jpg"><img src="/static/imghwm/default1.png" data-src="http://www.31358.cn/wp-content/uploads/2011/12/image001_thumb3.jpg" class="lazy"   style="max-width:90%" title="image001" alt="image001" border="0"  style="max-width:90%"></a> </p>
<p>如果您返回 清单 4,就会注意到在加载主交易之后,您对这些交易的每个部分都调用了 <code>loadDetails</code> 函数。在这个函数中,您通过使用 eBay Shopping API 加载每个交易的附加细节 — 但前提是浏览器支持 Web Workers。清单 5 展示了 <code>loadDetails</code> 函数。 </p>
<p><a name="l5"><b>清单 5. 预取交易细节</b></a></p>
<pre class="brush:php;toolbar:false">function loadDetails(items){
    if (!!window.Worker){
        items.forEach(function(item){
            var xmlStr = null;
            if (window.<a title="localStorage" href="http://www.31358.cn/localtorage/">localStorage</a>){
                xmlStr = <a title="localStorage" href="http://www.31358.cn/localtorage/">localStorage</a>.getItem(item.itemId);
            }
            if (xmlStr){
                var itemDetails = parseFromXml(xmlStr);
                dealDetails[itemDetails.id] = itemDetails;
            } else {
                var worker = new Worker("details.js");
                worker.onmessage = function(message){
                    var responseXmlStr =message.data.responseXml;
                    var itemDetails=parseFromXml(responseXmlStr);
                    if (window.localStorage){
                        localStorage.setItem(
                                        itemDetails.id, responseXmlStr);
                    }
                    dealDetails[itemDetails.id] = itemDetails;
                };
                    worker.postMessage(item.itemId);
            }
        });
    }
}

loadDetails 中,您首先检查全局作用域(window 对象)中的 Worker 函数。如果该函数不在那里,那么无需做任何事。反之,您首先检查 XML 的 localStorage 以获取这个交易的细节。这是移动 Web 应用程序常用的本地缓存策略,本系列第 2 部分.详细介绍过这种策略。

如果 XML 位于本地,那么您在 parseFromXml 函数中解析它并将交易细节添加到 dealDetails 对象。反之,则衍生一个 Web Worker 并使用 postMessage 向其发送 Item ID。当这个 Worker 检索到数据并将数据发布回主线程后,您解析 XML,将结果添加到 dealDetails,然后将 XML 存储到 localStorage 中。清单 6 展示了这个 Worker 脚本:details.js。

清单 6. 交易细节 Worker 脚本

importScripts("common.js");
onmessage = function(message){
    var itemId = message.data;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200){
            postMessage({responseXml: this.responseText});
        }
    };
    var urlStr = generateUrl(itemId);
    xhr.open("GET", "proxy?url=" + escape(urlStr));
    xhr.send(null);
}

这个 Worker 脚本非常简单。您使用 Ajax 调用代理,该代理又调用 eBay Shopping API。当您收到来自代理的 XML 后,使用一个 JavaScript 对象文字(object literal)将其发送回主线程。注意,即使您能够使用来自一个 Worker 的 XMLHttpRequest,但所有信息都将返回它的 responseText 属性,而不是它的 responseXml 属性。这是因为这个 Worker 脚本范围内没有 JavaScript DOM 解析器。注意,generateUrl 函数来自 common.js 文件(见 清单 7)。您使用 importScripts 函数导入 common.js 文件。

清单 7. Worker 导入的脚本

function generateUrl(itemId){
    var appId = "YOUR APP ID GOES HERE";
    return "http://open.api.ebay.com/shopping?callname=GetSingleItem&"+
        "responseencoding=XML&appid=" + appId + "&siteid=0&version=665"
            +"&ItemID=" + itemId;
}

现在,您已经知道如何(为支持 Web Workers 的浏览器)填充交易细节,我们返回 图 1 研究一下如何在应用程序中使用这种方法。注意,每笔交易旁边都有一个 Show Details 按钮,单击该按钮修改这个 UI,如 图 2 所示。

图 2. 显示的交易细节

 image001

这个 UI 将在您调用 showDetails 函数时显示。清单 8 展示了这个函数。

清单 8. showDetails 函数

function showDetails(id){
    var el = $(id);
    if (el.style.display == "block"){
        el.style.display = "none";
    } else {
        el.style.display = "block";
        if (!el.innerHTML){
            var details = dealDetails[id];
            if (details){
                var ui = createDetailUi(details);
                el.appendChild(ui);
            } else {
                var itemId = id;
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function(){
                    if (this.readyState == 4 &&
                                      this.status == 200){
                        var itemDetails =
                                        parseFromXml(this.responseText);
                        if (window.localStorage){
                            localStorage.setItem(
                                              itemDetails.id,
                                              this.responseText);
                        }
                        dealDetails[id] = itemDetails;
                        var ui = createDetailUi(itemDetails);
                        el.appendChild(ui);
                    }
                };
                var urlStr = generateUrl(id);
                xhr.open("GET", "proxy?url=" + escape(urlStr));
                xhr.send(null);
            }
        }
    }
}

您收到了即将显示的交易的 ID 并切换是否显示它。当该函数第一次调用时,它将检查细节是否已经存储到 dealDetails 映射中。如果浏览器支持 Web Workers,那么这些细节已经存储且它的 UI 已经创建并添加到 DOM 中。如果这些细节还没有加载,或者,如果浏览器不支持 Workers,那么您需要执行一个 Ajax 调用来加载此数据。这就是这个应用程序无论在有无 Workers 时都同样能正常工作的原因。这意味着,如果 Workers 受到支持,那么数据就已被加载且 UI 将立即响应。如果没有 Workers,UI 仍将加载,只是需要花费几秒钟时间。

结束语

对于 Web 开发人员来说,Web Workers 听起来就像一种外来的新技术。但是,如本文所述,它们是非常实用的应用程序。这对于移动 Web 应用程序来说尤其正确。这些 Workers 可用于预取数据或执行其他预先操作,从而提供一个更加实时的 UI。这对于需要通过网速可能较慢的网络加载数据的移动 Web 应用程序来说尤其正确。结合使用这种技术和缓存策略,您的应用程序的快捷反应将使您的用户感到惊喜!

Statement
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
How to Add Audio to My HTML5 Website?How to Add Audio to My HTML5 Website?Mar 10, 2025 pm 03:01 PM

This article explains how to embed audio in HTML5 using the <audio> element, including best practices for format selection (MP3, Ogg Vorbis), file optimization, and JavaScript control for playback. It emphasizes using multiple audio f

How to Use HTML5 Forms for User Input?How to Use HTML5 Forms for User Input?Mar 10, 2025 pm 02:59 PM

This article explains how to create and validate HTML5 forms. It details the <form> element, input types (text, email, number, etc.), and attributes (required, pattern, min, max). The advantages of HTML5 forms over older methods, incl

How do I use the HTML5 Page Visibility API to detect when a page is visible?How do I use the HTML5 Page Visibility API to detect when a page is visible?Mar 13, 2025 pm 07:51 PM

The article discusses using the HTML5 Page Visibility API to detect page visibility, improve user experience, and optimize resource usage. Key aspects include pausing media, reducing CPU load, and managing analytics based on visibility changes.

How do I use viewport meta tags to control page scaling on mobile devices?How do I use viewport meta tags to control page scaling on mobile devices?Mar 13, 2025 pm 08:00 PM

The article discusses using viewport meta tags to control page scaling on mobile devices, focusing on settings like width and initial-scale for optimal responsiveness and performance.Character count: 159

How do I handle user location privacy and permissions with the Geolocation API?How do I handle user location privacy and permissions with the Geolocation API?Mar 18, 2025 pm 02:16 PM

The article discusses managing user location privacy and permissions using the Geolocation API, emphasizing best practices for requesting permissions, ensuring data security, and complying with privacy laws.

How to Create Interactive Games with HTML5 and JavaScript?How to Create Interactive Games with HTML5 and JavaScript?Mar 10, 2025 pm 06:34 PM

This article details creating interactive HTML5 games using JavaScript. It covers game design, HTML structure, CSS styling, JavaScript logic (including event handling and animation), and audio integration. Essential JavaScript libraries (Phaser, Pi

How do I use the HTML5 Drag and Drop API for interactive user interfaces?How do I use the HTML5 Drag and Drop API for interactive user interfaces?Mar 18, 2025 pm 02:17 PM

The article explains how to use the HTML5 Drag and Drop API to create interactive user interfaces, detailing steps to make elements draggable, handle key events, and enhance user experience with custom feedback. It also discusses common pitfalls to a

How do I use the HTML5 WebSockets API for bidirectional communication between client and server?How do I use the HTML5 WebSockets API for bidirectional communication between client and server?Mar 12, 2025 pm 03:20 PM

This article explains the HTML5 WebSockets API for real-time, bidirectional client-server communication. It details client-side (JavaScript) and server-side (Python/Flask) implementations, addressing challenges like scalability, state management, an

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools