Wednesday, June 29, 2011

Javascript Non Blocking development

Symptoms: You  have a javascript code that blocks your other script or even the UI.  And you are scratching your head now :)

Most of the modern browsers are using a single "thread" or "process" to handle both UI update and javascript execution (mostly update the UI as well).  And think about this "thread" as the browser UI queue, whenever you have javascript needs to be executed, it will be put into the queue along with other UI updates made by the browser.

And when the javascript code execute, everything else (other scripts and even the UI) will be waiting for that to be finished.  And if that piece of javascript code is a long running script, it will make the user experience very slow or the page will even be stalled.

There are several ways to handle this javascript blocking issue, or in the other words, we are using non-blocking javascript development.

  • The easiest one, place your script at the end of the page, before the end of the body tag.  When javascript is downloading and execute, it will halt the browser rendering, and by placing the <script> at the end of the body tag,  it will give users a full look and feel experience when the page loads. Since the <script> is at the end, so it will start downloading and executing after all initial DOM elements are rendered.
  •  Dynamic loading script.  This requires a little bit coding (yay, just a little bit). What you need to do is waiting till the DOM is ready, you create the <script> tag dynamically.  Once the "src" is executed, the browser will start to download the javascript file and execute the stuff.  In this way, the javascript won't block any browser UI, since it will yield the browser UI before download / execute.
  • If you have a very long/tight javascript loops, your loops could block the browser UI updates, or even cause the browser to stop your script.  In this case, you may want to split your loops by using setTimeout() / setInterval() to delay each execution.  In this way, all other browser UI will have a chance to be updated.
  •  Besides setTimeout() / setInterval(), you can make use of the html5 features of the webworkers.   By using webworkers, you are "outsourcing" some heavy processes to individual "webworkers".  The effect of the web-worker is opening a "new thread" for each call.

There are some links I found may help :-


No comments:

Post a Comment