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:
To add one or more script references to the loader use queueScriptReference method:
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:
Actually the loadScripts expects more parameters, but only first is required. The declaration of loadScripts function in AJAX library looks like this:
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:
Test.js file contains the following code:
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:
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:
and js file:
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:
Alert button says the script is not loaded yet - that's true. Now after we load the script (clicking on first button):
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.
1 comment:
Little long but really an amazing creation I have seen here.
Post a Comment