HTML5   发布时间:2022-04-25  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了HTML5 New Feature Series: Web Workers大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
As we kNow,client-side JavaScript runs in single thread,in other words,JavaScript and UI rendering program share the main thread,that means,UI rendering will be blocked when JavaScript is working on high-loading processing,thereby user experience will be serIoUsly reduced. As one of HTML5 features,Web Workers create a new running mechanism to make JavaScript run an extra thread in new environment,so that we can do some time-consuming tasks. And next,let's learn the details related to Web Workers.
In short,Web Workers can create an independent work thread via loading an external script file,and then run the task out of main thread. CreaTing a work thread is pretty simple,just like the following code:
var worker = new Worker('js/worker.js');@H_197_7@As the code shows,we only need to provide the path of script file as a parameter in the constructor of the 'Worker' object,and then,a Web Worker instance will be created,and the work thread will be running behind the UI. It should be noted that we're only able to load the script file of the same origin in our project due to the same-origin policy. 

And when creaTing work thread has done,we can message with it in main thread,and that utilizes the 'postmessage' function to send message to work thread,in work thread,we can capture the 'message' event to receive message from main thread. In 'postmessage' function we can pass variety of data types,but note that,some special BOM objects are excluded,such as 'document'.
Now let's see how does it work in main thread:
//message sending
worker.postmessage({name: 'Scott'});

//message receiving
worker.onmessage = function(event) {
	var data = event.data;
	//to do
}@H_197_7@Similarly,in work thread we can also use 'postmessage' and 'onmessage' functions to send or receive message from main thread,below is the code in worker.js file: 

//message sending
self.postmessage({name: 'Worker'});

//message receiving
self.onmessage = function(event) {
	var data = event.data;
	//to do
}@H_197_7@In certain circumstances,we have no choice but to interrupt the running work thread,in main thread we can use the 'terminate' method,and in work thread we can call 'close' method of worker instance to interrupt it self,just like the following code shows: 

//interrupt a work thread in main thread
worker.terminate();

//interrupt work thread it self
self.close();@H_197_7@ 

The above shows some basic usage of Web Workers,and next let's show a real scenario in an example.

Usually we will join some technology groups to discuss the latest technologies and to get acquainted with other guys,make friends. Assume that we want to look for someone in the group,it's quite inconvenient when group is to large,therefore,we plan to add a searching functionality to this group,make it easy to get the matched data by keywords,just like the following picture shows:

HTML5 New Feature Series: Web Workers


In this case,the group data has been loaded to client in advance,and the searching functionality will be achieved entirely in client,if the data is too large,this simple searching probably can cause a certain decline on user experience. Hence,we plan to implement this manipulation by Web Workers. Now let's take a look at the basic structure of the example project:

HTML5 New Feature Series: Web Workers


We can easily see,there is a worker.js file in js folder,it's used to put the logic of work thread,and it will be loaded by main thread at runtime,we're going to explain it later. Now let's take a glance at the structure in main page:

<html>
	<head>
		<title>Web Worker</title>
		<link rel="stylesheet" type="text/css" href="css/main.css">
	</head>
	<body>
		<div id="searching">
			<input id="keywords" type="text" placeholder="type in to start searching">
			<button id="search-button" onclick="search();">search</button>
			<div id="members">
				<!-- <div class="member">
					<img src="img/icon.png">
					<div class="info">
						<p>John Li</p>
						<p>Java progrAMMing,Python language</p>
					</div>
					<a class="add">+Add</a>
				</div> -->
				<!-- the search results will be here -->
			</div>
		</div>
		<script type="text/javascript" src="js/jquery.js"></script>
		<script type="text/javascript" src="js/main.js"></script>
	</body>
</html>@H_197_7@ 

Looks pretty simple,contains a search input and search button,below them is the search result display area. In order to get it to run,we also need the collaboration of main.js,below is the code:

//a simple group member data example
var groupMembers = [
	{
		id: 101,name: 'John Li',skills: 'Java progrAMMing,Python language,MysqL'
	},{
		id: 102,name: 'Lisa Wang',skills: 'HTML,JavaScript,CSS,Node.js'
	},{
		id: 103,name: 'Tom Wang',skills: 'JavaScript,HTML5'
	},{
		id: 104,name: 'Andy Zhang',skills: 'PHP Language,JavaScript progrAMMing,CSS'
	}
	/*
		a large number of data
	*/
];

//loading the worker.js to instantiate a Worker object
var worker = new Worker('js/worker.js');

//receive message from work thread,and then render the result data
worker.onmessage = function(E) {
	renderGroupMembers(e.data.results);
};

function search() {
	var keywords = $('#keywords').val().trim();
	
	//post a message to work thread
	worker.postmessage({
		groupMembers: groupMembers,keywords: keywords
	});
}

function renderGroupMembers(members) {
	var html = '';
	members.forEach(function(member) {
		var resultHtml = '<div class="member">'
			 		   + '	<img class="icon" src="img/icon.png">'
			 		   + '	<div class="info">'
			 		   + '		<p>' + member.name + '</p>'
			 		   + '		<p>' + member.skills + '</p>'
			 		   + '	</div>'
			 		   + '	<a class="add">+Add</a>'
			 		   + '</div>';
		html += resultHtml;
	});

	$('#members').html(html);
}

renderGroupMembers(groupMembers);@H_197_7@In the code snippet,we will load the worker.js firstly,and then instantiate a Worker object,after that capture the message event,and then show the result data in corresponding area. and the search function is responsible for listening button click event,and post a message to work thread carrying the group data and search keywords to hand over the task to work thread. 

And Now let's figure it out how does worker.js work:

//receive the message from main thread
self.onmessage = function(E) {

	var groupMembers = e.data.groupMembers;
	var keywords = e.data.keywords;

	var results = searchByKeywords(groupMembers,keywords);

	//post the result message to main thread
	self.postmessage({results: results});
};

//it may be quite complicated in Real Application
function searchByKeywords(groupMembers,keywords) {
	var results = [];

	keywords = keywords.toLowerCase();

	groupMembers.forEach(function(member) {
		var nameMatched = member.name.toLowerCase().indexOf(keywords) > -1;
		var skillsmatched = member.skills.toLowerCase().indexOf(keywords) > -1;
		
		if (nameMatched || skillsmatched) {
			results.push(member);
		}
	});

	return results;
}@H_197_7@In the above code,at first we captured the message event in work thread to receive the group data and keywords,and then called search function,at last sent BACk the results to main thread,the whole searching finished. 

Above is the details of Web Worker's usage,and in real development we may face with many complicated operations in client,in this scenario we can consider Web Workers to be the best choice to complete the complex task in work thread,and then reduce UI block in main thread,if so we will get a significant improvement on user experience.

大佬总结

以上是大佬教程为你收集整理的HTML5 New Feature Series: Web Workers全部内容,希望文章能够帮你解决HTML5 New Feature Series: Web Workers所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。