Saturday, December 18, 2010

Make JavaScript-heavy webpage load faster

It is cleaner to put all your JavaScript files or scripts inside the "<header>" tag. However, browsers must interpret these scripts completely before going on to render the page content. And during interpretation, nothing is shown on the web page, offering no response to users' screen and making the website seem slow to load. 

Remember that most people will leave your page if it takes more than 5 seconds to show anything. Thus, include scripts in the body immediately before you need to use them. The browser will render whichever content available first and show it to users. It only have to interpret the scripts when it needs to. This will offer great feedback to users, letting them know your page is loading and making your page seems to load faster than it actually is! Here is a example of this technique: 
<html>  
  <head>  
    //we need this first so interpret this here <script type="text/javascript" src="xxx.js" />
  </head>
  <body>
     //Page content goes here
     //we need this later so interpret it later <script type="text/javascript" src="aaa.js" />  
  </body>
</html>


Warning: this doesn't mean that you can spread your scripts all over the page. Always try to externalize your scripts as much as possible and include the external files when you need them. Obey Object-Oriented Design :)
As always, if you have any question please feel free to post in the comment section below. 

No comments:

Post a Comment