Tuesday, March 11, 2008

On-Demand JavaScript

When we load a lot of JavaScript code during initial page load, it can immensely slowdown the page display. The user will be staring at a blank page until all the JavaScript code gets downloaded and executed, which isn't going to exactly help your PR.
 
One workaround is to load the JS code in stages. This way it is possible to initially display a bare-bones page, and we keep building on it, as the JS modules pour in.
 
How to do this
 
Following is a DOM based approach, which appends a <script> tag to the <head> tag of the document. Now there are other methods to do this, which we will look into in later posts.
 
function getCode() {
  if (self.graphScript) { // Already exists
   return;
  }
  var head = document.getElementsByTagName("head")[0];
  script = document.createElement('script');
  script.id = 'graphScript';
  script.type = 'text/javascript';
  script.src = "dash.js";
  head.appendChild(script);
}
 
The code in this case is downloaded asynchronously, hence immediately using the script after loading it might not work. In most cases, using the script will actually fail the first time, because the download function will return before the script's been downloaded.
 
We can add a timeout function which periodically checks for the script load. Or if its your own code add a function call to the loading page at the end of the script being loaded, which tells the loading page that it has arrived safe and secure.
 
 

No comments: