Here is a clean way to initialize all the JavaScript in your ASP.NET page. It is accomplished using a custom initializer class. This example uses jQuery.
In the master page itself or in a .js class referenced in your master page, declare your class:
function Initializer() {
this.functionArray = new Array();
}
Initializer.prototype.addStep = function (func) {
this.functionArray.push(func);
}
Initializer.prototype.init = function () {
for (x in this.functionArray) {
this.functionArray[x]();
}
}
The init()
method loops through the function array and executes each method.
Add this block to the master page:
<script type='text/javascript'>
var initializer = new Initializer();
$(document).ready(function () {
initializer.init();
});
</script>
In your user controls and/or pages, add your initialization code:
private void CreateInitScript()
{
string script = "function doSomething() {
//Perform some actions
}";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterClientScriptBlock(this.GetType(), "MyScript", script, true);
string validationScript = "if(initializer){ initializer.addStep(doSomething); }";
cs.RegisterStartupScript(this.GetType(), "initscript", validationScript, true);
}
This code is very handy when you want to handle your control's initialization at the same time as the hosting page and the master page if you use one.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.