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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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….

Method 2

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?

Method 3

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

Method 4

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

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

Method 5

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x