Tuesday, January 26, 2010

An introduction to ASP.NET Ajax 4: The Scriptloader

The Scriptloader tries to make the complexity of loading scripts easier.

Core features

The core features of the Scriptloader are:
  • Automatically resolving dependencies
  • Lazy loading
  • Parallel loading
Automatically resolving dependencies

You need the Start script to start using the Scriptloader. Use Sys.require to load the component(s) you need. The dependencies get resolved automatically. In this example I load the DataContext component.


   1:  <html>
   2:      <title>ScriptLoader Demo</title>    
   3:      <head>
   4:          <script src="http://ajax.microsoft.com/ajax/beta/0911/Start.debug.js" type="text/javascript"></script>
   5:          <script type="text/javascript">
   6:              //Enable debugging
   7:              Sys.Debug = true;
   8:              
   9:              //Resolve dependencies
  10:              Sys.require([Sys.scripts.DataContext]);                 
  11:          </script>
  12:      </head>
  13:      <body>
  14:      </body>
  15:  </html>


Using Internet Explorer developer tools you can see all the extra scripts are downloaded. The Scriptloader downloaded all the DataContext's dependencies automatically.



Lazy loading

In this example the scripts get downloaded in the background after clicking the button.

   1:  <html>
   2:      <title>ScriptLoader Demo</title>    
   3:      <head>
   4:          <script src="http://ajax.microsoft.com/ajax/beta/0911/Start.debug.js" type="text/javascript"></script>
   5:          <script type="text/javascript">
   6:              //Enable debugging
   7:              Sys.Debug = true;    
   8:                                  
   9:              //Lazy Loading
  10:              function doSomething(){
  11:                  Sys.require([Sys.scripts.DataContext]);
  12:              };
  13:              
  14:          </script>
  15:      </head>
  16:      <body> 
  17:          <input type="button" onclick="doSomething()" value="Do something"/>
  18:      </body>
  19:  </html>


Parallel loading

Using the script tag makes scripts load in serial. If you use the Scriptloader, the scripts get loaded in parallel, improving performance.

Apply this to your own scripts

The Scriptloader is also capable of loading other scripts. Find out how on the ASP.NET Ajax Wiki.

No comments:

Post a Comment