简体   繁体   中英

How to run a block of code in background in Jquery

I am building a Mobile Application using Jquery Mobile and PhoneGap. I am using a Single Page Model , whereby I have something like index.html, login.html etc

I have written a javascript that always contact the server side for new messages every 5 minutes using setInterval() and all works well in background without interfering with what the user is doing.

I want to ask if it is possible to declare and run this block of code globally instead of having to re-declare it in every html page.

Note: I am using rel="external" in the links in jQuery Mobile which causes each page to refresh when a user navigate to a page.

我相信你主要担心的是当另一个脚本被加载时它会覆盖前一个计时器,所以如果剩下一分钟直到下一次调用,现在有5个。为了克服这个障碍你可以按顺序添加一种逻辑到你的间隔在一天中的特定时间运行,例如9.00,9.05,9.10 ...这样,每次执行脚本时都应该清除InterInterval并重置它,以便下次执行代码时是针对浏览器计算的标准时间约会时间。

I guess u can use web workers for this purpose, they work within a global context and independently , like threads , and they are really efficient which allows you to even perform I/O.

Please check this link, Hope this helps you

https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers

https://groups.google.com/forum/#!topic/phonegap/SMMEwYXUjCU

It will be more feasible if you use the concept of MVC in your project . Try to make a base class which is used by the other classes . you can use the concept of jquery widget too

I think this should work...

  1. Creating a page (master page) that its only job is to run a timer...
  2. On the master page add an iframe (set to 100% visibility) and point the iframe to your other pages...

What this will do, is that everytime one of your pages (in the iframe) postback, the master page will be kept in memory and the timer will not get reloaded...

Sample master page.

<html>
 <head>
  <script>
   function checkMessages() {
    // check messages here
    setInterval(...);
    }
  </script>
 </head>
 <body onload="checkMessages();">
     <iframe id="iframe1" src="subpage.aspx" width="100%" scrolling="auto" frameborder="no" marginheight="0" marginwidth="0" height="100%"></iframe>
 </body>
</html>

I was able to use Android Background Service to achieve what I wanted. I used a plugin with PhoneGap. For those who want to use similar technique, you can get the info about the plugin on phonegap-service-tutorial-part-1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM