Monday, May 12, 2008

Loading and Executing JavaScript Files From JavaScript, ASP.NET AJAX

Download source code with samples for the article here.

Quite often we need to load js files dynamically right from javascript. With ASP.NET AJAX it is simple.

ASP.NET AJAX library has internal ScriptLoader class that can be used to load js files, specify callbacks that will be invoked when script is downloaded and ready, and execute functions inside newly loaded files.

I will not list all available methods from ScriptLoader class - you can see them in more details in AJAX source.

I will demonstrate how to load files and execute some functions in it.

ScriptLoader has static and instance members. To add script references(urls) and script blocks to the loader we have to create instance of the class:

image

To add one or more script references to the loader use queueScriptReference method:

image

the parameter is path to the script file.

And finally to load the file and insert link element to the body of the document use the following function:

image

 

Actually the loadScripts expects more parameters, but only first is required. The declaration of loadScripts function in AJAX library looks like this:

image

As you see the function can accept three callback functions that will be called when some condition is true: load was successful, load failed, or load was timed out.

 

Whole sample will look like:

image

Test.js file contains the following code:

image

First line simply executes alert function.

Second line is very important - this is how ScriptLoader knows when script is loaded to the end and calls success callBack.

If you don't add this line to the end of the file ScriptLoader will never know is or is not script executed (loaded) to the end.

Lets run the page:

 image

Script was loaded and executed!

 

Now lets try another example, where we will pass callback to the function to be able to call function inside dynamically loaded file, and be sure that it is loaded before we call anything in it.

The page will look like:

image

and js file:

image

As you see we are calling the function inside file in callback, this way we ensure it is called AFTER file was loaded.

Lets execute the page and first try to click second button:

image

Alert button says the script is not loaded yet - that's true. Now after we load the script (clicking on first button):

image

Is works.

 

You may be wondering why you need this. But suppose you are loading contents to the browser dynamically, for example using web service or page method call, and the content is using javascript. You can also load dynamically it's script file and execute anything you need there.

 

Hope this helps.

 

Technorati Tags:

 

kick it on DotNetKicks.com

1 comment:

Server Transfer said...

Little long but really an amazing creation I have seen here.