Microsoft's Social Web Guy

James Senior on social + web

How the Script Loader in the Microsoft Ajax Library will make your life wonderful

October 15
by James 15. October 2009 21:33

Everyone in the Microsoft Ajax team has a favorite feature, the CDN, jQuery Integration, and mine happens to be the Script Loader. I’m fond of it because it has some really cool features that aid the performance of my web application and take away much of the headache associated with organizing and loading any scripts that I use either from Microsoft, my own application or indeed a third party library like jQuery. The headache I’m referring to can be best characterized in the example below where I am loading scripts needed to use controls from the Ajax Control Toolkit (ACT) and the various components of the Microsoft Ajax Library. There are multiple scripts required and prior to the Script Loader I would be bringing them in all manually and having to worry myself with loading them in the right order. Not fun.

 

  1. // Microsoft Ajax Library scripts
  2.     <script type="text/javascript" src="../Scripts/MicrosoftAjax/MicrosoftAjaxCore.js"></script>
  3.     <script type="text/javascript" src="../Scripts/MicrosoftAjax/MicrosoftAjaxComponentModel.js"></script>
  4.     <script type="text/javascript" src="../Scripts/MicrosoftAjax/MicrosoftAjaxSerialization.js"></script>
  5.     <script type="text/javascript" src="../Scripts/MicrosoftAjax/MicrosoftAjaxGlobalization.js"></script>
  6.     <script type="text/javascript" src="../Scripts/MicrosoftAjax/MicrosoftAjaxTemplates.js"></script>
  7.  
  8.     // ACT Controls
  9.     <script src="../Scripts/ACT/ACTRegisterExtended.js" type="text/javascript"></script>
  10.     <script src="../Scripts/ACT/ACTWatermark.js" type="text/javascript"></script>
  11.     <script src="../Scripts/ACT/ACTExtenderBase.js" type="text/javascript"></script>
  12.     <script src="../Scripts/ACT/ACTCommon.js" type="text/javascript"></script>

This can all be made better – let’s find out how by starting at the beginning with start.js.

Getting started with the script loader

Start.js is your friend. It contains the Script Loader which is super small and knows about all the scripts of the Microsoft Ajax Library, some of which are listed in the above sample. You include it just as you would any other script like so:

  1. <script type="text/javascript" src="../scripts/start.js"></script>

It’s also available via our brand spanking new, smoking fast Microsoft Ajax CDN so your customers will get blisteringly fast script downloads wherever they are in the world. ScottGu’s got more info on the CDN here.

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

Now that you’ve got the Script Loader bootstrapped it’s time to “harness the power of the atom” (Scott Hanselman’s favorite saying at the moment) and start loading scripts into your application. The Script Loader allows you to load libraries and scripts into your application without having to worry about where the code file is. Now this is where it gets sexy (yes JavaScript can be sexy). In the following example I want to use the dataView control and the ApplicationServices script (both included in Microsoft Ajax Library) so I tell the Script Loader to get them ready for me using “Sys.require”:

  1. <script src="../Scripts/MicrosoftAjax/start.js" type="text/javascript"></script>
  2. <script type="text/javascript">
  3.  
  4.     // Load required scripts for DataView client control, using script Loader
  5.     Sys.require([Sys.components.dataView, Sys.scripts.ApplicationServices], function () {
  6.  
  7.         // do some stuff with dataView and Application Services
  8.  
  9.     });
  10.  
  11. </script>

Once the Script Loader fetches them (in parallel) and executes them it checks if the DOM is ready and then calls the function I’ve specified in the second parameter of Sys.require. On a side note, we can also bring in jQuery by adding Sys.scripts.jQuery to the array.

Let’s take it further by considering a common scenario where I have created a custom script for my application. The script is only needed when a user clicks a certain button though, so we’re going to register it with the Script Loader but only execute it on-demand when (this is an example of what we call “lazy loading”):

  1. <script src="../Scripts/MicrosoftAjax/start.js" type="text/javascript"></script>
  2. <script src="../Scripts/RegisterMyAppScript.js" type="text/javascript"></script>
  3.  
  4. <script type="text/javascript">
  5.  
  6.     function useMyCustomScript() {
  7.  
  8.         Sys.require(Sys.scripts.myAppScript, function () {
  9.             // Use my custom script
  10.         });
  11.  
  12.     }
  13.             
  14. </script>
  15.  
  16. <input type="button" onclick="useMyCustomScript()" value="Click me"/>

“But wait”, I can hear you say, “what is that extra script we reference – “RegisterMyAppScript.js”? Good question – that’s where we define our script and any other scripts that it depends on.

Let’s be definitive

Within RegisterMyAppScript.js we use the Script Loader’s “defineScripts” method to make it aware of the location of our script and any dependencies that it may have on other scripts:

  1. Sys.loader.defineScripts({
  2.         releaseUrl: "%/../CustomScripts/{0}.js",
  3.         debugUrl: "%/../CustomScripts/{0}.js"
  4.     },
  5.         [
  6.             { name: "myAppScript",
  7.                 executionDependencies: ["ApplicationServices"],
  8.                 isLoaded: !!(window.My && My.Scripts && My.Scripts.TheScript)
  9.             }
  10.         ]
  11.     );

First we specify a release and debug URL and depending on how we’ve setup the loader it will use a minified version or a version with comments and intellisense (we’ll get into that later). Then we pass a parameter to defineScripts that provides the information about the different scripts we want to register – in our case “myAppScript”. For each script we specify the name (filename without the file extension) its execution dependencies and an isLoaded test that we use to check if the script has already been loaded (we don’t want to load it again!)

If this were a custom control we were loading then we could also tell the Script Loader under which namespace our behaviors are loaded.

Now we can let the Script Loader worry about the fact that my custom script requires ApplicationServices from the Microsoft Ajax library and it will load all the required scripts in parallel, maximizing performance whilst only executing them when they are ready.

Next we’ll look at what the actual custom script looks like.

Parallel Power with dependency management built in

In the past, loading scripts in sequence made sense when you had complex dependencies that tied the scripts together however this is not recommended practice if performance is important. Let us assume that both having modular code (dependencies) and good performance is important to you. Whilst browsers have been able to load two scripts in parallel for some time, modern browsers let you load many at once but this in itself can raise a couple of problems. Firstly, we have a “race condition” where Script A is racing against Script B to be loaded and executed. When there are dependencies between A and B and the dependent script loads first (for whatever reason) your code will break because it is expecting a symbol to be present that has yet to be loaded and executed by the browser. Secondly, only modern browsers allow us to load more than two scripts in parallel (there are some hacks you can do but let’s assume we’re not using them), so if we have a large collection of scripts with dependencies we will still be waiting an undesirable length of time.

The Script Loader allows us to download multiple scripts in parallel whilst managing all their dependencies and making sure that we only execute the scripts once a dependency is satisfied.

There’s one more question that needs answering though. How do we load the scripts, like RegisterMyAppScript.js, without executing them automatically? We solve this problem by wrapping the script in an execute function and then check to see if the Script Loader is ready (loaded). If it’s ready to rock then we then call registerScript, passing in the name of the component and the execute callback function. Now the loader knows that this is the script that must be called when all its dependencies are in place – and that execute is the function to make this happen.

  1. (function() {
  2.         function execute() {
  3.             // .. script content ..
  4.         }
  5.      
  6.         if (window.Sys && Sys.loader) {
  7.             Sys.loader.registerScript(“myAppScript”, null, execute);
  8.         }
  9.         else {
  10.             execute();
  11.         }
  12.     })();

You’ll notice that if the Script Loader is not there (for whatever reason) then we just go ahead and execute the script anyway – with this we are preserving the original functionality of the script.

Power to the developer

A lot of developers are scared by JavaScript development. However, more recently with the introduction of libraries like Microsoft Ajax Library and jQuery as well as better intellisense support and browser debugging there is no longer much of a reason to hide behind the cushions. Remember earlier on where we specified a release and debug version of the scripts? The Script Loader has a property we can set to enable a debug mode which when we are running our scripts and stepping through them using our favorite browser plugins is really useful. When set to true the loader uses the version which is not minified and has comments so we can figure out where our script is going wrong.

  1. Sys.debug = true;


Summary

That’s it for now but there is a bunch more features in the Script Loader that I will cover off in future blog posts, including:

  • Lazy Loading
  • Intellisense in Visual Studio
  • How the loader does the ordering of scripts
  • Handling DOM ready events etc

In this blog post we’ve seen how script loading and management of execution is made easier using the Script Loader from the Microsoft Ajax Library as well as covering off how we handle dependencies between different scripts and debugging.

To find out more about what’s in the Microsoft Ajax Preview 6 release check out the following resources and be sure to come to Microsoft PDC where we’ll be doing sessions on the new stuff!

Tags:

ASP.NET | Microsoft Ajax Library

Bookmark and Share
Permalink | Comments (82) | Post RSSRSS comment feed

Comments

10/16/2009 5:26:20 PM #

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        Microsoft's Social Web Guy | How the Script Loader in the Microsoft Ajax Library will make your life
        [jamessenior.com]
        on Topsy.com

topsy.com

10/16/2009 5:30:32 PM #

trackback

Microsoft's Social Web Guy | How the Script Loader in the Microsoft Ajax Library will make your life wonderful

Thank you for submitting this cool story - Trackback from DotNetShoutout

DotNetShoutout

10/16/2009 6:04:55 PM #

pingback

Pingback from channel9.msdn.com

Announcing Microsoft Ajax Library Preview 6 | jsenior | Channel 9

channel9.msdn.com

10/16/2009 6:14:10 PM #

trackback

Microsoft Ajax Library Preview 6

The ASP.NET team has been cranking away on more AJAX goodness…this time with a significant update to

BillS IIS Blog

10/19/2009 11:00:40 AM #

pingback

Pingback from updatepanel.wordpress.com

Microsoft AJAX Library Preview 6 Available «  Update Panel .NET

updatepanel.wordpress.com

10/20/2009 9:54:31 AM #

Angel

Is it possible to use the Client Script Loader with javascript files that are embedded in an assembly?

Thanks.

Angel Bulgaria

10/22/2009 7:43:18 AM #

pingback

Pingback from charged.co.za

Announcing Microsoft Ajax Library Preview 6 | CHARGED's Digital Lifestyle at Work or Play

charged.co.za

10/23/2009 1:37:02 AM #

james

@angel - it's not possible right now. The Script Loader is intended for client side not server side development.

james United States

10/23/2009 2:58:31 PM #

Ryan

Can the script loader be used for custom javascript files or is it just used for ACT and Microsoft Ajax Library?

Ryan United States

10/27/2009 12:45:25 PM #

launceston laptops

I am not a big fan of .NET but I am certainly a fan of ajax and script loader, they make things simpler for user and ajax is on the rise recently and its being used on blog engine and I have noticed some popular plugins in wordpress too have ajax built in to it.

launceston laptops United States

11/4/2009 2:28:21 AM #

Scott Wade

Is there documentation that details or lists the possible values (namespaces) that are supported by the Preview 6 Script Loader, specifically for including any supported AjaxControlToolkit scripts-only files?

For instance, your example includes a Sys.require(dataView, Sys.scripts.ApplicationServices],

Scott Wade United States

12/10/2009 9:23:41 PM #

Vincent Therry

Do we have to write the Sys.loader.registerScript and the execute function or you just described how it is implemented behind the scene ?

Thanks, this script loader seems very great !

Vincent Therry France

2/1/2010 3:08:05 PM #

Robin Webb

I've just started looking at the AJAX client script loader and have been evaluating the benefits.

Having added a local reference to "start.js" in my web page and a sys.require on jQuery (below):

<script src="Scripts/MicrosoftAjax/Start.js" type="text/javascript"></script>

    <script type="text/javascript">
        Sys.require(Sys.scripts.jQuery);

        Sys.onReady(function() {
            alert("ok");
        });
    </script>

I noticed that the 1.3.2 library version of jQuery is being loaded from the CDN URL. How would I go about forcing the start.js to load scripts from my local intranet web server that doesn't have internet access to CDN?

For example, I would want to load 1.3.2-min.js from a local web server within my work environent.

I guess that there is probably an easy answer to this question.

Robin Webb United Kingdom

2/1/2010 7:30:00 PM #

james

Scott - check out the learn section on http://www.asp.net/ajax

james United States

2/1/2010 7:31:24 PM #

james

Vincent, yes the Script Loader needs the execute method in place to manage running the script at the right time based on dependencies.

james United States

2/1/2010 7:35:10 PM #

james

Hey Robin

Check this how-to out: http://www.asp.net/ajaxlibrary/HOW%20TO%20Choose%20Local%20or%20Remote%20Scripts.ashx

Cheers
James

james United States

2/2/2010 9:40:04 AM #

Classic Monte Carlos

Excellent read about script loaders, thanks for another great post.

Classic Monte Carlos United States

2/2/2010 6:23:02 PM #

repossessed cars

I really appreciate the pictures. It really goes along way to help us noobies. Thanks again!

repossessed cars United States

2/3/2010 2:04:20 AM #

Acnezine

The pictures are great. Love them too

Acnezine United Kingdom

2/3/2010 2:06:11 AM #

Bowtrol

This script has really made my life easier man.Thanks for your effort.

Bowtrol United States

2/3/2010 6:56:09 AM #

Capervan Hire Australia

Script works well except in Mozilla for me anyway.

Capervan Hire Australia Australia

2/4/2010 7:03:40 AM #

property talk

I really love this article, so much depth and content.

property talk United States

2/4/2010 2:21:24 PM #

Forex Vps

Its really wonderful and watchable. I like to share it with all my friends and hope they will definitely like it.

Forex Vps United States

2/5/2010 4:20:00 PM #

Acompanhantes Belo Horizonte - MG

I loved the content of the post.

Acompanhantes Belo Horizonte - MG Brazil

2/5/2010 9:18:19 PM #

Acompanhantes

Amazing article!
It does make my life wonderful Wink
I´ll apply these info in my next projects.
Thanks a lot!

Acompanhantes Brazil

2/7/2010 12:18:15 PM #

acompanhantes de luxo

That a good advance and good explanation about AJAX. Anyway, it d be great to see incompatibilites with disabled people... that is to say usability...

acompanhantes de luxo France

2/7/2010 11:33:21 PM #

ED

Really interesting articles. I enjoyed reading it. Are these genuine images or has the artwork been touched up they are truly. Thanks for sharing a nice info.

ED Russia

2/8/2010 7:22:14 AM #

pokerstars

Awesome post! Interesting info to know.

pokerstars United States

2/8/2010 12:11:21 PM #

Acompanhantes Belo Horizonte - MG

very good your text.

Acompanhantes Belo Horizonte - MG Brazil

2/9/2010 12:02:47 AM #

mens jewelry

You just saved me about 6 hours a day in work! If only my boss knew we could automate this hehehe

much appreciated.

mens jewelry United States

2/9/2010 10:09:21 AM #

best top 10 fighter rankings

I've surfed the net more than three hours today, however, I haven't found such useful information like yours. Thanks a lot, it's really useful for me.

best top 10 fighter rankings United States

2/15/2010 8:50:41 AM #

forex vps

How to use Remote Desktop Connection for the two systems which have same IP Address?

forex vps United States

2/16/2010 5:48:55 AM #

repo car

Thank you very much for posting this. It really helps for the screens. Laughing

repo car United States

2/16/2010 12:42:03 PM #

web designers melbourne


Useful info. Hope to see more good posts in the future.

web designers melbourne United States

2/17/2010 6:54:43 AM #

budget planning

great post. I enjoyed reading it

budget planning United States

2/18/2010 9:16:51 PM #

tattoo positions

I have noticed some popular plugins in wordpress too have ajax built in to it.

tattoo positions United States

2/18/2010 10:01:51 PM #

Criar Sites

Parabéns pelo comentário. Realmente muito interessante.

Criar Sites Brazil

2/18/2010 10:02:54 PM #

Acompanhantes em BH

Parabéns. Adoro!!!

Acompanhantes em BH Brazil

2/18/2010 10:04:12 PM #

Acompanhantes em BH

Interessante!!!

Acompanhantes em BH Brazil

2/18/2010 10:05:10 PM #

Acompanhantes em BH

Muito bom.

Acompanhantes em BH Brazil

2/18/2010 11:29:50 PM #

Contabilidade em Geral

Será mesmo???

Contabilidade em Geral Brazil

2/18/2010 11:30:39 PM #

Convite Especiais

É mentira!!!!

Convite Especiais Brazil

2/18/2010 11:31:45 PM #

Convite Especiais

Parabéns!!!!!!!

Convite Especiais Brazil

2/18/2010 11:33:00 PM #

Marmoraria

Obrigado pelo comentário!

Marmoraria Brazil

2/19/2010 4:12:34 PM #

Acompanhantes BH

Parabéns. Excelente post.

Acompanhantes BH Brazil

2/20/2010 6:13:18 AM #

Media

Can the script loader be used for custom javascript files or is it just used for ACT and Microsoft Ajax Library? @ thank for ask, my question is same.

Media United States

2/20/2010 10:49:43 AM #

Marmoraria

Legal!!

Marmoraria Brazil

2/20/2010 10:50:27 AM #

Bulk Ink

Será????

Bulk Ink Brazil

2/22/2010 10:06:39 AM #

Carissa Putri

Dear guys, I've surfed the net more than three hours today, however, I haven't found such useful information like yours. Thanks a lot, it's really useful for me.

Carissa Putri United States

2/22/2010 10:36:25 AM #

Article directory

Thanks a lot, it's really useful for me.

Article directory Norway

2/23/2010 3:45:39 AM #

insanity workout

Great post! I am just starting out in community management/marketing media and trying to learn how to do it well - resources like this article are incredibly helpful...

insanity workout United States

2/24/2010 10:26:01 AM #

Billy Flash

Useful post thanks.  I've been doing web dev since 1999 but I tend to focus more on Flash and multimedia, only recently getting into technologies like AJAX which is all still quite new to me, but glad I found this site, hope you have more gems like this!

Billy Flash United Kingdom

2/25/2010 8:05:58 AM #

REO Listings

I have been doing web dev too but not using ajax. I find it difficult but really interesting. I am more fond of php and database systems.

REO Listings United States

2/26/2010 1:25:22 PM #

webthesurfi rugs webdesign

wow..this article really helps me, i haven't found related article like this

webthesurfi rugs webdesign United States

2/26/2010 6:58:56 PM #

ED

Really interesting articles. I enjoyed reading it. Are these genuine images or has the artwork been touched up they are truly. Thanks for sharing a nice info.

ED Russia

2/27/2010 10:35:35 PM #

Leopoldo Shrout

Sensible browse, sensible points, a number of which I've got learned along the way still (humility, grace, layoff the controversial stuff). Can share with my colleagues at work as we have a tendency to begin blogging from a company perspective.

Leopoldo Shrout Switzerland

2/27/2010 11:27:54 PM #

Anjelica Deshaw

I would name your blog the dreamland! While Santa knocks at our door just once per year, you blog is open the whole year - wow!  Thank you.

Anjelica Deshaw Switzerland

2/28/2010 6:31:21 AM #

Article directory

Those pictures really helped. Thank you very much and an excellent article.

Article directory United States

2/28/2010 3:52:55 PM #

Watch Pacquiao Clottey

Great tutorial! This makes me to be convinced to use this platform for my new blog: Pacquiao vs. Clottey blog. Thank you for imparting your knowledge and skills sir!

Watch Pacquiao Clottey United States

2/28/2010 10:34:26 PM #

Lewis Dobson

Well i have to agree with other comments on here, this blog is fantastic!!! thanks very much i hope to read more of your posts.

Regards,
Lewis

Lewis Dobson United Kingdom

2/28/2010 10:35:08 PM #

Latest UK Weather

Well i have to agree with other comments on here, this blog is fantastic!!! thanks very much i hope to read more of your posts.

Regards,
Lewis

Latest UK Weather United Kingdom

3/1/2010 3:06:12 AM #

Detox diet guide

Was having a problem with the script loader for a few days and those screenshots really helped a lot! Thank you for sharing this.

Detox diet guide United States

3/2/2010 12:51:54 AM #

ipad apps

so good to see an honest bloggers work.

ipad apps United States

3/2/2010 9:45:21 AM #

mma pound for pound fighting

Hello author, I've surfed the net more than three hours today, however, I haven't found such useful information like yours. Thanks a lot, it's really useful for me.

mma pound for pound fighting United States

3/2/2010 6:37:48 PM #

webcam tchat

Excellent post!

webcam tchat United States

3/2/2010 6:40:37 PM #

Video web cam

Nice blog and very interesting posts! I'll come back for more...

Video web cam United States

3/2/2010 7:46:22 PM #

Privat cam

I see that your blog is very appreciated ...

Privat cam United States

3/3/2010 1:18:58 AM #

Herbey Smith

Your website is loading very slow for me. Might just be my isp but i dunno... anyways . Very helpful, many thanks. Will definitely bookmark your blog for future reference Smile Would you mind checking out my site for <A href="http://www.freexboxlivegoldcodes.com/"> free xbox live gold</A>?

Herbey Smith United States

3/3/2010 1:19:22 AM #

Herbey Smith

Your website is loading very slow for me. Might just be my isp but i dunno... anyways . Very helpful, many thanks. Will definitely bookmark your blog for future reference Smile Would you mind checking out my site for <A href="http://www.freexboxlivegoldcodes.com/"> free xbox live gold</A>?

Herbey Smith United States

3/3/2010 8:34:26 AM #

cheap vps

This is one of the best post I have ever read, I would love to read more in future. Keep up the good work.

cheap vps United States

3/3/2010 10:19:27 PM #

Accounting

your informatioan about scribt loader in microsoft ajax is helpfull for me.this article hope continued

Accounting United States

3/5/2010 4:34:28 AM #

mayweather-mosley

Great tutorial! I have been doing web dev too but not using ajax. I find it difficult but really interesting. I am more fond of php and database systems. This makes me to be convinced to use this platform for my new blog. Thank you for imparting your knowledge and skills sir!

mayweather-mosley Republic of the Philippines

3/5/2010 8:00:25 PM #

Article

Great post !

Article Oman

3/5/2010 8:06:36 PM #

Deidre Tilghman

Sensible scan, sensible points, some of which I've got learned along the way likewise (humility, grace, layoff the controversial stuff). Will share with my colleagues at work as we tend to begin blogging from a corporate perspective.

Deidre Tilghman Switzerland

3/5/2010 8:24:08 PM #

Erasmo Ming

Indeed a great blog post. The eye to detail simply for this post is just as impressive as all of the sites detail above. Nice work, and a sensible read.

Erasmo Ming Switzerland

3/5/2010 8:30:10 PM #

Mike Stauss

Sensible read, smart points, a number of that I have learned along the manner furthermore (humility, grace, layoff the controversial stuff). Will share with my colleagues at work as we have a tendency to begin blogging from a corporate perspective.

Mike Stauss Switzerland

3/5/2010 9:03:55 PM #

Acompanhantes BH

Very post man.

Acompanhantes BH Brazil

3/6/2010 1:26:04 AM #

baby slings carriers

Very interesting post I have seen here.Thanks for posting it.

baby slings carriers United States

3/8/2010 4:29:02 PM #

stimulus bill new home buyer tax credit

[...] Microsoft's Social Web Guy | How the Script Loader in the Microsoft Ajax Library will make your life wonderful - www.jamessenior.com/.../...our-life-wonderful.aspx - first time home buyer To be eligible, buyers cannot have owned a home for the past three years, and the new home has to be used as a primary residence...  home buyer stimulus - http://stimulushomebuyer.info [...]

stimulus bill new home buyer tax credit United States

3/10/2010 3:29:37 PM #

Sydney Brothels Review

Very interesting post I have seen here.Thanks for posting it.

Sydney Brothels Review United States

3/10/2010 7:19:24 PM #

Checks

Thanks for sharing nice stuff. Actually I thought of writing same stuff in my personal hub But not as good as you have written. Any how thanks for sharing such a valuable stuff. I have bookmarked yoru site.

Checks Canada

3/10/2010 8:08:03 PM #

how to buy foreclosures

I hapen to agree with sherry above.  I will look the information and post it here.  We'll have the FACTS momentarily.

how to buy foreclosures United States

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading