Lazy Loading JavaScript Files Using ASP.NET AJAX Script Loader

The ASP.NET AJAX Script Loader control will make your life easier. Gone are the days where you have to include a multi-line block of script includes on every web page. Gone are the days of double checking to make sure your script files are included in the right order. Now with the appropriate use of the Script Loader’s require function gone are the days of having to load scripts on your page whether you need them or not.

Since the Script Loader control programmatically loads scripts into the browser you get imperative control of when and where scripts are loaded. Consider a page that will only load the dataView scripts on to the page when a user tries to access an area of the page where an ASP.NET AJAX client template is used to display the data. The following code demonstrates how to accomplish this task.

Note: Make sure to see it in action by checking out the live working copy!

Script

<script src="http://weblogs.asp.net/Scripts/MicrosoftAjax/start.js" type="text/javascript"></script>
<script type="text/javascript">

Sys.require(Sys.scripts.ComponentModel);

Sys.onReady(function()
{
    Sys.addHandler($get("bindButton"), "click", function()
    {
        $get("bindButton").disabled = true;
        Sys.require([Sys.components.dataView], function()
        {
            Sys.create.dataView("#dv", { data: colors });
        });
    });
});

var colors = [
   { Name: "Black" },
   { Name: "Blue" },
   { Name: "White" },
   { Name: "Green" }
];
</script>

Markup

<input type="button" value="Get Colors" id="bindButton" name="bindButton" />
<ul id="dv" class="sys-template">
    <li>{{Name}}</li>
</ul>

Special thanks to Julian Dominguez (@juliandominguez) for helping me work out a few kinks in the first iteration of this code :)

Published Wednesday, December 9, 2009 2:12 PM by craigshoemaker
Filed under: ,

Comments

No Comments