2013 jsdc webworker
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

2013 jsdc webworker

  • 4,250 views
Uploaded on

隨著Web Application的發展,前端開發越來越複雜,多執行緒的需求也慢慢浮現,本議題主要介紹何謂Web Worker,到底能做到什麼,不能做到什麼,以及實際案例的分享。

隨著Web Application的發展,前端開發越來越複雜,多執行緒的需求也慢慢浮現,本議題主要介紹何謂Web Worker,到底能做到什麼,不能做到什麼,以及實際案例的分享。

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,250
On Slideshare
3,168
From Embeds
1,082
Number of Embeds
10

Actions

Shares
Downloads
55
Comments
0
Likes
19

Embeds 1,082

http://blog.blackbing.net 976
http://blackbing.logdown.com 64
http://feeds.feedburner.com 28
http://digg.com 4
http://cloud.feedly.com 3
http://feedly.com 2
http://localhost 2
http://www.linkedin.com 1
http://feedproxy.google.com 1
https://www.linkedin.com 1

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Bingo2013/05/191Web WorkerWhat theSunday, May 19, 13
  • 2. About Me• front-end Engineer at• http://blog.blackbing.net• blackbing@gmail.com• https://www.facebook.com/blackbing2Sunday, May 19, 13
  • 3. Hello Web Worker3Sunday, May 19, 13
  • 4. In the beginning4if (heard?)if (heard? && used?)if (heard? && used? && frustrated?)if (heard? && used? && used_in_project?)Sunday, May 19, 13
  • 5. Web WorkerA web worker, as defined by the World Wide Web Consortium(W3C) and the Web Hypertext Application Technology WorkingGroup (WHATWG), is a JavaScript script executed from an HTMLpage that runs in the background, independently of other, user-interface scripts that may also have been executed from the sameHTML page. Web workers are able to utilize multi-core CPUs moreeffectively.http://en.wikipedia.org/wiki/Web_worker5Sunday, May 19, 13
  • 6. Web Worker6http://en.wikipedia.org/wiki/Web_workerA web worker, as defined by the World Wide Web Consortium(W3C) and the Web Hypertext Application Technology WorkingGroup (WHATWG), is a JavaScript script executed from an HTMLpage that runs in the background, independently of other, user-interface scripts that may also have been executed from the sameHTML page. Web workers are able to utilize multi-core CPUs moreeffectively.Sunday, May 19, 13
  • 7. 7Sunday, May 19, 13
  • 8. UI Blocking?• javascript is single-threaded• UI rendering• executing javascript8http://www.nczonline.net/blog/2010/08/10/what-is-a-non-blocking-script/Sunday, May 19, 13
  • 9. Boss said...91+2+3+...+nSunday, May 19, 13
  • 10. That’s easy!function getsum(max) {var cnt = 0;var sum = 0;while (cnt <= max) {sum += cnt++;}return sum;}10Sunday, May 19, 13
  • 11. 11getsum(1,000)getsum(100,000)getsum(1,000,000,000)杯具Sunday, May 19, 13
  • 12. DEMO12http://blackbing.github.com/WorkerD/why.htmlSunday, May 19, 13
  • 13. 13Sunday, May 19, 13
  • 14. 14Sunday, May 19, 13
  • 15. 1+2+..+n =15Sunday, May 19, 13
  • 16. 16Sunday, May 19, 13
  • 17. Don’t jump into Web Workerfor using Web Worker.17If you just think it’s cool,you’ll be frustrated.Sunday, May 19, 13
  • 18. 18Sunday, May 19, 13
  • 19. Expectation19It should be faster.It should be easy to use.It should avoid blocking UI.Sunday, May 19, 13
  • 20. CAN I USE it on Desktop?20http://caniuse.com/#search=worker100%Sunday, May 19, 13
  • 21. CAN I USE it on Mobile?21http://caniuse.com/#search=workerSunday, May 19, 13
  • 22. CAN I USE it on Mobile?22http://caniuse.com/#search=worker100%(!?)Sunday, May 19, 13
  • 23. 23Sunday, May 19, 13
  • 24. new Workervar worker = new Worker(worker.js);worker.postMessage(something);worker.onmessage = function(e) {console.log(Worker said: , e.data);});24self.onmessage = function(e) {self.postMessage(e.data);};MasterWorkerSunday, May 19, 13
  • 25. var worker = new Worker(worker.js);worker.postMessage(something);worker.addEventListener(message, function(e) {console.log(Worker said: , e.data);}, false);25self.addEventListener(message, function(e) {self.postMessage(e.data);}, false);MasterWorkernew WorkerSunday, May 19, 13
  • 26. Worker cannot access• window• DOM• document• parentis undefinedis undefinedis undefinedis undefined26Sunday, May 19, 13
  • 27. Pass window object?worker.postMessage(window);27MasterSunday, May 19, 13
  • 28. postMessage28worker.postMessage({number: 1234,reg: /[d]+/ig,boolean: true,object: {foo:bar},array: [foo,bar]})MasterSunday, May 19, 13
  • 29. postMessage29worker.postMessage({number: 1234,reg: /[d]+/ig,boolean: true,object: {foo:bar},array: [foo,bar],func: function(){//this is a function}})MasterSunday, May 19, 13
  • 30. 30http://ajaxian.com/archives/an-implausibly-illustrated-introduction-to-html5-web-workersSunday, May 19, 13
  • 31. Worker can use• navigator• location(read-only)• XMLHttpRequest• setTimeout/setInterval• Basic Javascript data Structure andFunction(Math, Date, Array, etc.)31Functions available to workers : https://developer.mozilla.org/en-US/docs/DOM/Worker/Functions_available_to_workersSunday, May 19, 13
  • 32. 32Web Workers in IE10: Background JavaScript Makes Web Apps FasterSunday, May 19, 13
  • 33. Debug33worker.addEventListener(error, function(error){console.error(error.message);console.error(error.filename);console.error(error.lineno);});MasterSunday, May 19, 13
  • 34. Import Scripts34importScripts("http://underscorejs.org/underscore.js")no jQuery, Backbone, etc.WorkerSunday, May 19, 13
  • 35. Release Worker35worker.terminate()self.close()MasterWorkerSunday, May 19, 13
  • 36. Cost36Sunday, May 19, 13
  • 37. Use CasePrefetching and/or caching data for later use• Code syntax highlighting or other real-time text formatting• Spell checker• Analyzing video or audio data• Background I/O or polling of web services• Processing large arrays or humungous JSON responses• Image filtering in <canvas>• Updating many rows of a local web database37Sunday, May 19, 13
  • 38. front-end is more and more• upload image: resize/rotate/filtering• upload/download file format: use aformat for the server, translatingother format in client side.38powerfulSunday, May 19, 13
  • 39. Client-Server39ClientServer Server Server ServerSunday, May 19, 13
  • 40. Client-Server40Master HTMLWorker Worker Worker WorkerSunday, May 19, 13
  • 41. Background tasks run while userinteracting• auto save the draft of article• syntax highlighting• log user’s behavior(mouse tracking,clicking, etc...)• prefetching data• predicting user behavior• Generate complicated html template41Sunday, May 19, 13
  • 42. Mobile• Limited capability on mobile• Multicore CPU42Sunday, May 19, 13
  • 43. Real world usage• Syntax highlighting : ace code editor(Bespin)• Crypto : SHA1 Checksum Calculator• Graphics/image• snowCam• arborjs: http://arborjs.org/• A User-Driven Web OS: http://grimwire.github.io/grimwire• parallel.js: http://adambom.github.io/parallel.js/• Post huge data to server43Sunday, May 19, 13
  • 44. Wanna Try?• http://webworkersandbox.com/44Sunday, May 19, 13
  • 45. Brief Summary• What is web worker?• Basic usage• onMessage/postMessage• Debug• Use case and real world usage45Sunday, May 19, 13
  • 46. Known Issue• create worker in worker, but it iscurrently not support in Chrome• Crash when trying to use manyWebworkers46Sunday, May 19, 13
  • 47. Problems• Break dependency• Hardly debug• Troublesome on postMessage47Sunday, May 19, 13
  • 48. Break dependency48worker = new Worker(/worker_path/my_worker.js);define (require)->require jquerycar = require lib/carplane = require lib/planebreak requirejs dependencyMasterSunday, May 19, 13
  • 49. inline Worker49var jscontent = require(text!workerScript/inline_worker.js);var blobWorker = new Blob([jscontent], {type:application/javascript});var blobWorker_url = URL.createObjectURL(blobWorker);URL.revokeObjectURL(blobWorker_url);inlineWorker.terminate();var inlineWorker = new Worker(blobWorker_url);require text pluginMasterRelease resourceSunday, May 19, 13
  • 50. Hardly debug50worker.addEventListener(error, function(error){console.error(error.message);console.error(error.filename);console.error(error.lineno);});no console !?MasterSunday, May 19, 13
  • 51. Troublesome on postMessage51var worker = new Worker(worker.js);worker.postMessage({type: task1, data:blabla});worker.postMessage({type: task2, data:blabla});worker.postMessage({type: task3, data:blabla});....self.addEventListener(message, function(e) {var data = e.data;var type = data.type;if(type === task1)//blablablaelse if(type === task2)//blablabla//......etc}, false);MasterWorkerSunday, May 19, 13
  • 52. Passing Massive Data52worker.postMessage({//it is a very very complicated JSON})WorkerUI still block!MasterSunday, May 19, 13
  • 53. Solution• Split the data• Transferable Object53Sunday, May 19, 13
  • 54. Split data54WorkerSunday, May 19, 13
  • 55. Transferable Object55worker.postMessage({number: 1234,reg: /[d]+/ig,boolean: true,object: {foo:bar},array: [foo,bar],ref_object: object_from_closure,})worker.postMessage(this is a string);Workerstructured cloningFreeeeze!!MasterSunday, May 19, 13
  • 56. pass Transferable Object56worker.postMessage(arrayBuffer, [arrayBuffer]);var SIZE = 1024 * 1024 * 32; // 32MBvar arrayBuffer = new ArrayBuffer(SIZE);var uInt8View = new Uint8Array(arrayBuffer);var originalLength = uInt8View.length;for (var i = 0; i < originalLength; ++i) {uInt8View[i] = i;}worker.postMessage(uInt8View.buffer, [uInt8View.buffer]);MasterSunday, May 19, 13
  • 57. Feature Detection57var ab = new ArrayBuffer(1);worker.postMessage(ab, [ab]);//If the buffer is transferred and not copied,its .byteLength will go to 0:if (ab.byteLength) {alert(Transferables are not supported in your browser!);} else {// Transferables are supported.}http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-FastMasterSunday, May 19, 13
  • 58. Expectation?58It must be faster.It should be easy to use.It should avoid blocking UI.Cost of creating WorkerHardly to set up dependencyif we need to pass massive dataSunday, May 19, 13
  • 59. WorkerD59https://github.com/blackbing/WorkerDbower install WorkerDSunday, May 19, 13
  • 60. Why D?60Sunday, May 19, 13
  • 61. Benefitsworker.send(count, {s:1, e:10})syntax sugarself.on(count, function(data){//data is {s:1, e:10}})MasterWorkerSunday, May 19, 13
  • 62. 62consoleconsole.log/error/time/etc...require(["./car""./wheel"], (Car, Wheel) ->car = new Car(red)wheel = new Wheel(iron))requireWorkerWorkerBenefitsSunday, May 19, 13
  • 63. Example63jscontent = require(text!inline_worker.js)$(#sum_with_worker).on(click, ->loading()worker = new WorkerD(inlineWorker_js)worker.send(getSum, sumMax)worker.on(gotSum, (event, data)->log "gotSum: #{data}"loaded()))@on "getSum", (max) ->sum = cnt = 0while(cnt<=max)sum += cnt++self.send(gotSum, sum)MasterWorkerSunday, May 19, 13
  • 64. console64@on "getSum", (max) ->console.group getSumconsole.time getSumconsole.log getSumconsole.log maxsum = cnt = 0while(cnt<=max)sum += cnt++console.log sumself.send gotSum, sumconsole.log inlineWorker send messageconsole.timeEnd getSumconsole.groupEnd getSumWorkerSunday, May 19, 13
  • 65. Live Demo65http://blackbing.github.com/WorkerD/sandbox.htmlSunday, May 19, 13
  • 66. Real World Example66Sunday, May 19, 13
  • 67. 67https://c9.ioSunday, May 19, 13
  • 68. 68http://antimatter15.github.io/js-typed-array-sha1/Sunday, May 19, 13
  • 69. 69http://arborjs.org/Sunday, May 19, 13
  • 70. 70https://start.htc.comSunday, May 19, 13
  • 71. 71http://adambom.github.io/parallel.js/Sunday, May 19, 13
  • 72. 72前端效能提升方案Web Worker 神器Web Worker老木!?做!就對了!Sunday, May 19, 13
  • 73. More Reading73http://www.html5rocks.com/en/tutorials/workers/basics/http://social.msdn.microsoft.com/Search/en-US?query=web%20worker&ac=5Sunday, May 19, 13
  • 74. Thank you74Sunday, May 19, 13
  • 75. We are hiringfront-end Engineer75 https://www.facebook.com/blackbingSunday, May 19, 13