2016-07-26 6 views
0

DOMオブジェクトの更新をバックグラウンドで実行しようとしています。JavaScriptワーカーを使用してDOMオブジェクトを時間間隔で更新する

私は何を意味することは、更新タブのタイトル、およびユーザーは、私がすでに判明

(新しい通知があることを示すために)アクティブかどうかのタブを持っている場合、その労働者は、それが実行時に使用する必要がありますに関係なく、いくつかの要素でありますバックグラウンドで(しかし、DOMにアクセスすることはできません)。次のようにしようとしました:

メインHTML:最初の呼び出しが動作しない(イベントカウントが正しく設定されている)が、もう存在しているのJavaScriptファイル

function setEventsCount(count, appName, eventsTxt) { 
    var bell, text, countPar; 
    if (count > 0) { 
     bell = '<i class="fa fa-bell"></i>&nbsp;'; 
     countPar = '(' + count + ') '; 
     text = bell + eventsTxt + countPar; 
     $(".event-menu-li").html(text); 
     $("#event-menu-icon").html(bell + count) 
     document.title = countPar + appName; 
    } else { 
     bell = '<i class="fa fa-bell-o"></i>&nbsp;'; 
     text = bell + eventsTxt; 
     $(".event-menu-li").html(text); 
     $("#event-menu-icon").html(bell) 
     document.title = appName; 
    } 
} 

onmessage = function (e) { 
    var appUrl = e.data[0]; 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) { 
      postMessage(xmlhttp.responseText); 
     } 
    }; 
    xmlhttp.open("GET", appUrl, true); 
    xmlhttp.send(); 
} 

...some html 

<script> 
$(document).ready(function ($) { 
    if (window.Worker) { 
     console.log('[DEBUG] Worker is supported') 
     var eventsWorker = new Worker("<c:url value="/resources/js/eventTimer.js" />"); 
     setInterval(eventsWorker.postMessage([appUrl]), 20 * 1000); 
     //setEventsNonWorker() 
     eventsWorker.onmessage = function (e) { 
      console.log('Message received from worker' + e.data); 
      setEventsCount(e.data, appName, eventsTxt); 
     } 
    } else { 
     console.log('[DEBUG] Worker is NOT supported') 
     setEventsNonWorker() 
    } 
}); 
function setEventsNonWorker(){ 
    //regular update with setTimout and stuff 
} 

労働者20秒後に呼び出す

答えて

0

これは間違ったplエース

htmlが

//...  
eventsWorker.postMessage([appUrl]); 
eventsWorker.onmessage = function (e) { 
    console.log('Message received from worker' + e.data); 
    setEventsCount(e.data, appName, eventsTxt); 
//... 

であるべきだろうただのinit労働者、worker.jsはタイムアウト

//... 
onmessage = function (e) { 
    var appUrl = e.data[0]; 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) { 
      postMessage(xmlhttp.responseText); 
     } 
    }; 
    xmlhttp.open("GET", appUrl, true); 
    xmlhttp.send(); 
    setInterval(function() { 
     xmlhttp.open("GET", appUrl, true); 
     xmlhttp.send(); 
    }, 20*1000); 
} 
を持っている必要がありながら、
関連する問題