Home / AJAX

HOW TO Use On-demand Script Loading

Modified on 2009/12/04 17:26 by Stephen Walther Categorized as Uncategorized
Many Ajax applications rely on features that aren't required to be available when a page initially loads. For example, an application may have a print button that a user can click to print the page or may click another button that performs various calculations or business rules. The scripts that are executed to print or perform calculations don't need to be loaded when the page first loads since they won't be used until the end user interacts with the page. Loading the scripts after the page has loaded and rendered makes more sense in this type of scenario.

Loading scripts later in the page life-cycle is referred to as "lazy loading" and can have a significant impact on the start-up time of a page and allow the user to interact with the application more quickly. Although lazy loading of scripts was possible in the past using different JavaScript frameworks or custom coding techniques, the ASP.NET Ajax Library's Script Loader makes it straightforward to lazy load scripts in an application to enhance performance.

The Script Loader provides built-in support for lazy loading through Sys.require or Sys.loadScripts. To use Sys.require a metadata file defining the scripts to load must be created. Sys.loadScripts can also be used to lazy load scripts as users click a button or perform another type of action. The following code sample demonstrates how the Script Loader can use lazy loading to retrieve additional scripts as a user interacts with a page. The key part of the code sample is shown in the Calculate function.

<script src="http://ajax.microsoft.com/ajax/beta/0911/Start.js" type="text/javascript"></script>

<script type="text/javascript">

function Calculate() { Sys.loadScripts(["../Scripts/Rules.js", "../Scripts/Calculations.js"], function() { //Perform calculations }); }



<input type="button" onclick="Calculate()" value="Calculate" />

As the page loads only Start.js will be retrieved from the server as shown in Figure 1.


Figure 1. By using the Script Loader's lazy loading feature only the required scripts have to be retrieved when the page first loads.

As the Calculate button is clicked the Calculate function is called which uses Sys.loadScripts to lazy load two scripts behind the scenes (see Figure 2). There will be a slight delay while the scripts are loaded but it's a onetime delay since the scripts will be cached by the browser for future page visits.


Figure 2. The Rules.js and Calculations.js scripts are lazy loaded behind the scenes by the the Script Loader.

By placing Sys.loadScripts in the Calculate function the custom scripts will be lazy loaded behind the scenes by the Script Loader. Once they're available, the callback function will be called and the code that uses the scripts can be executed.
  Name Size
- LazyLoading1.jpg 8.56 KB
- LazyLoading2.jpg 15.32 KB