×
Get in touch

Get in touch with Binary

Binary Studio website uses cookies to enhance your browsing experience. By continuing to use our site, you agree to our Privacy Policy and use of cookies.

Learn more more arrow
Agree
Binary Studio 19.10.2011

Javascript optimization


Downloading resources in parallel mode

Modern browsers can download resources in several threads. But in some cases threads can be blocked. External script in <head> section may block downloading subsequent resources. This is why it is better to include all cascade style sheets in the beginning of <head> section, and all external scripts at the end (Properly including stylesheets and scripts).

The other way is to use “defer” and “async” html attributes, which force browser to download scripts in asynchronous mode.

Dynamic script linking

There are several ways to link external scripts dynamically:

  • document.write(‘<script src=”.........”></script>’);
  • document.createElement(“script”);
  • XMLHttpRequest

The worst is document.write(), as it blocks DOMLoaded event from triggering. Using document.createElement() is better, as it doesn’t block DOMLoaded event. But it shows page loading indicator at the top of page. The best solution is to use XMLHttpRequest. It provides total control on script loading process.

Javascript optimization.

Reflow/relayout

To speed up DOM manipulation routines modern browsers use separate rendering tree. When script modifies some DOM properties no reflow/relayout occurs. Affected elements in render tree are just marked as “dirty”. Relay out occurs only when page is (re)drawn or when script tries to read property of “dirty” element. One should remember that undue reading of DOM properties may lead to continue reflow. So it is much faster to read and calculate all required values first and only then update, than to update during reading. (Minimizing browser reflow).

 

Sergey G., Senior developer, Head of PHP department

Binary Studio