Running JavaScript on first page load/post back

October 2, 2012

I have had a few occasions where I’ve needed to run JavaScript on a page at first load only, or the oppposite – on a post back only. This can be achieved as follows:

<script type="text/javascript" language="javascript">

	function pageLoad(sender, args)
	    alert('Runs on every page load');

		if (args.get_isPartialLoad())
			alert('Runs on partial post back only');
        } else {
            alert('Runs on initial load only');

The other way is to conditionally use ClientScriptManager.RegisterClientScriptBlock(), using Page.IsPostBack to determine if this is the first load or a postback. Note that if you are using UpdatePanels (AJAX) on your page, you need to use ScriptManager.RegisterClientScriptBlock() instead, as ClientScriptManager.RegisterClientScriptBlock() will not survive a partial postback.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: