使用JavaScript Worker以时间间隔更新DOM对象

时间:2016-07-26 18:51:32

标签: javascript html5 dom

我正在尝试在后台进行一些DOM对象更新。

我的意思是更新标签标题,以及一些元素,无论用户是否有标签处于活动状态(以显示有新通知)

我已经发现,必须使用Worker才能在后台运行(但无法访问DOM)。试过如下:

主要HTML:

...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
}

工作者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();
}

第一个电话正在工作(事件计数已正确设置),但在20秒内没有其他电话

1 个答案:

答案 0 :(得分:0)

好的,事实证明我把错误放在错误的地方

html应该是

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

只是init worker,而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);
}