February 19, 2009

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

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

3 Responses to "How to execute javascript onLoad only once in an ASP.NET page"
  1. darenkov said...
    February 19, 2009 3:56 PM

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

  2. Suprotim Agarwal said...
    February 20, 2009 3:45 AM

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

  3. Anonymous said...
    September 29, 2009 7:08 AM

    How in PHP?

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions