How to execute javascript onLoad only once in an ASP.NET page

If you are working on a ASP.NET Master/Content Page scenario and have declared a javascript onload, then the script gets executed every on every postback.

However if you would like to execute it only once during the first postback, then here's how to do so:
Copy this code in the <head> of your MasterPage



<script type="text/javascript">


function invokeMeMaster() {


var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';


if (chkPostBack == 'false') {


alert('Only the first time');


}

}



window.onload = function() { invokeMeMaster(); };


</script>



The code determines if there is a postback in Javascript and then executes code based on the result. Hence the alert popup is shown only once.

You can several other tips related to calling JavaScript in Master/Content Pages over here:

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

4 comments:

darenkov said...

This throws and error. BC30037: Character is not valid. I think it has something to do with the angle brackets.

Suprotim Agarwal said...

Please post the entire code over here and I will have a look at it.

Anonymous said...

How in PHP?

Marcus Geckos said...

This site prevents the posting of any tags other than bold, italics or link.
But if you create a simple aspx page and add your suggested javascript you will see that it returns a
"Compiler Error Message: BC30037: Character is not valid."
Put simply the .net 2 server doesn't like
var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';