views:

92

answers:

5

I have a Javascript. I want to call only at page load. I dont want to call at postbacks.. (Asp.net 3,5)

+1  A: 

Try out the Page.IsPostback property http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

Jan_V
You might want to combine this with the ClientScript.RegisterStartupScript technique so that the script is only added inside if (!Page.IsPostBack) {}
Daniel Dyson
+1  A: 
<html>
<head>

</head>
<body onload="javascript:yourFunctionCall()">

</body>
</html>
Neurofluxation
That will still run on postback
Joel Coehoorn
This will be called in Postback.
Darin Dimitrov
@Darin and @Joel you are so right..
Jack
This way you do not eat computer time to add strings, code etc.
Aristos
+5  A: 

In your code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ClientScript.RegisterStartupScript(GetType(), "key", "someFunction();", true);
    }
}
Darin Dimitrov
Thanks but it didnt solve my problem.
Jack
If you want the script to run only once you could use a `Session` property which indicates whether the script has run and based on its value include or not the script.
Darin Dimitrov
Ok. I think it is impossible to run once at initialization of the masterpage life cycle.
Jack
How can I set value to Session? Because every page load Session value will be reset? I cant check session value and call javascript..
Jack
A: 

Better thing is to call your java script function at the tag on load. Here the java script calls only once.not in all post backs.

anishmarokey
A: 

You can also attach to the load event to avoid accidentally overriding the onload in the body tag with document.onload in JavaScript. This is usually only a problem with master pages having content pages implement their own load event and overriding the master page JavaScript.

<script type="text/javascript">
    function Page_loaded() {
        //Do Work
    }

    if (document.all) {
        //IE
        window.attachEvent('onload', Page_loaded);
    } else {
        //Everything else
        window.addEventListener('load', Page_loaded, false);
    }
</script>
MattPII