Click here to Skip to main content
13,139,132 members (63,853 online)
Click here to Skip to main content
Add your own
alternative version


5 bookmarked
Posted 11 Jul 2011

Clean ASP.NET page initialization

, 11 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Initialize Master Page, Page, and Controls in a single JavaScript call.

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:

//Initializer class
function Initializer() {
    //A simple array of functions
    this.functionArray = new Array();
//The method to insert functions to the initialization stack
Initializer.prototype.addStep = function (func) {
//The initializing method
Initializer.prototype.init = function () {
    for (x in this.functionArray) {

The init() method loops through the function array and executes each method.

Add this block to the master page:

<script type='text/javascript'>
    //Create instance of the initializer
    var initializer = new Initializer();
    //JQuery's 'onready' function
    $(document).ready(function () {

In your user controls and/or pages, add your initialization code:

//Method called by Page_Load
private void CreateInitScript()
    string script = "function doSomething() {
       //Perform some actions
    ClientScriptManager cs = Page.ClientScript;
    //Insert your script into the page
    cs.RegisterClientScriptBlock(this.GetType(), "MyScript", script, true);

    //Add a call to your method to the validation stack
    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 article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Gordon Kushner
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170915.1 | Last Updated 11 Jul 2011
Article Copyright 2011 by Gordon Kushner
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid