Yashwant Kumar Sahu
Yashwant Kumar Sahu

Reputation: 3386

How to run JavaScript code before page load?

I have working in asp.net web application. Here I need to run JavaScript before page load.

I have tried:

<body oninit="funinit();" onprerender="funRender();" onload="funload();">


</body>

 <script type="text/javascript" language="javascript">
    function funinit() {
        alert("funinit");
    }
    function funload() {
        alert("funload");
    }
    function funRender() {
        alert("funRender");
    }      

</script>

here only funload() is working.

Upvotes: 32

Views: 112879

Answers (5)

Pushpendra
Pushpendra

Reputation: 4382

You can use window.onpaint for such purpose like :

<script type="text/javascript">
    function preloadFunc()
    {
        alert("PreLoad");
    }
    window.onpaint = preloadFunc();
</script>

I hope it helps you....

Upvotes: 39

Safran Ali
Safran Ali

Reputation: 4497

try to put your script in head section of the page:

<head>
  <script type="text/javascript" language="javascript">
        alert("funinit");
        alert("funRender");
  </script>
</head>

Upvotes: 7

Madhur Ahuja
Madhur Ahuja

Reputation: 22681

Why not Use the ClientScriptManager.RegisterClientScriptBlock Method http://msdn.microsoft.com/en-us/library/btf44dc9.aspx

Upvotes: 2

Einacio
Einacio

Reputation: 3532

just insert a <script> tag wherever inside the body you want it to run. it will be executed as soon as the parser reads it, as long as it doesn't reference an element not yet created

Upvotes: 10

TJHeuvel
TJHeuvel

Reputation: 12608

Just inline it?

<script type='text/javascript'>
alert("funload");
</script>

Or put it in a function and call it immediately. Try to put it to the topmost of your page, however since the DOM isnt loaded yet you cant get any other elements.

What is it you want to do?

Upvotes: 15

Related Questions