//shared onconnect = function(e) { var port = e.ports[0]; port.postMessage('Hello World!'); port.onmessage = function(e) { port.postMessage('pong'); // not e.ports[0].postMessage! // e.target.postMessage('pong'); would work also } }
¡¡¡¡µÚÒ»ÖÖ·½·¨ÖÐÊÇʹÓÃʼþ¾ä±úµÄ·½Ê½½«Ìýmessageʼþ£¬²»ÐèÒªµ÷ÓÃworker.port.start(),µÚ¶þÖÖ·½·¨ÊÇͨ¹ýaddEventListener()·½·¨¼àÌýmessageʼþ£¬ÐèÒªworker.port.start()·½·¨¼¤»î¶Ë¿Ú¡£ËûÃDz»Í¬ÓÚworker£¬µ±ÓÐÈ˺ÍËûͨÐÅʱ´¥·¢connectʼþ£¬È»ºóËûµÄmessageʼþÊÇ°ó¶¨ÔÚmessagePort¶ÔÏóÉϵģ¬²»ÏëworkerÄÇÑù£¬Äã¿ÉÒÔ»ØÍ·¿´¿´workerÊÇÔõô×öµÄ¡£
¡¡¡¡ÄÇôsharedWorkerÊÇÔõô¹²ÏíÊý¾ÝµÄÄØ£¿Çë¿´ÏÂÃæµÄÀý×Ó¡£
¡¡¡¡
//main1 ºÍmain2¶¼ÊÇÕâÑù Shared workers: demo 2getset); ); ); ); ); worker.port.addEventListener((e) { log.innerText = e.data; }, false); worker.port.start(); // note: need this when using addEventListener set.addEventListener((e){ worker.port.postMessage(txt.value); },false); get.addEventListener((e){ worker.port.postMessage(); },false);
//shared var data; onconnect = function(e) { var port = e.ports[0]; port.onmessage = function(e) { if(e.data=='get'){ port.postMessage(data); }else{ data=e.data; } } }
¡¡¡¡ÕâÀï·ÖÎöÒ»²¨£¬ÎÒÃÇÔÚmain1.htmlµÄÎı¾¿òÊäÈëÊý¾Ý£¬µã»÷set£¬È»ºóÔÚmain2.htmlÖеã»÷get·¨ÏÖÄܹ»»ñÈ¡µ½ÎÒÃÇÔÚmain1.htmlÖÐÉèÖõÄÊý¾Ý£¬Õâ˵Ã÷ÎÒÃǵÄsharedWorkerÊÂʵÉÏÊǵ¥ÀýµÄ£¬¾ÍÏñjavaÖеÄstaticÀàÒ»Ñù£¬²»¹Ünew¶àÉÙ¸ö£¬Êµ¼ÊÉÏÖ»ÓÐÒ»¸ö£¬ÕâÑùÎÒÃǵIJ»Í¬Ï߳̾ͿÉÒÔ¹²Ïíµ½sharedWorkerÖеÄÊý¾ÝÁË¡£ÕâÀï°Ñͼ¸øÉÏ£¬¼ÇµÃÓÐƪÎÄÕÂû¸øͼ£¬È»ºóÓÐÈ˸øÎÒ½¨ÒéÁË£¬ÎÊÄܲ»Äܸøͼ¡£
¡¡¡¡
¡¡¡¡×îºóÀ´Ð¡½áһϣ¬workerºÍsharedWorkerûÓÐʲôÐüºýµÄ£¬¾ÍÊÇ°Ñ̨ǰµÄ¹¤×÷°áµ½Ä»ºóÈ¥×ö£¬²»´ò¶Į̈ǰµÄ¹¤×÷¡£ÕýËùν̨ÉÏÊ®·ÖÖÓ£¬Ì¨ÏÂÊ®Ä깦£¬Èç¹ûÄã°Ñ̨ϵÄÊ®Ä깩·Åµ½Ì¨ÉÏ×ö£¬¹ÛÖÚµÄÍÙÄÐÇ×ÓÔç¾Í°ÑÄãÑÍËÀÁË£¬ËùÒÔ˵ÄÇЩ·ÑÊ·ÑÁ¦µÄ¹¤×÷»¹ÊǷŵ½Ì¨ÏÂÈ¥£¬Ì¨ÉÏÖ»ÓÃչʾÄã×îºÃµÄÒ»ÃæµÄºÃÁË£¬Ê®·ÖÖÓ×ãÒÔ£¡
¡¡¡¡×î×îºó£¬Èç¹ûÄú¾õµÃÎÒµÄÎÄÕ¶ÔÄúÓÐËù°ïÖúµÄ»°£¬²»·Á¹Ø×¢Ò»ÏÂÎÒ£¬ÄúµÄÖ§³ÖÊǶÔÎÒ×î´óµÄ¹ÄÀø¡£
¡¡¡¡²Î¿¼£º
¡¡¡¡html5Óëcss3ȨÍþÖ¸ÄÏÉϲᣨ½£©
¡¡¡¡
¡¡