需要在body onload事件之前在web表单上运行Javascript

时间:2013-10-18 13:02:59

标签: javascript asp.net

我正在开发一个asp.net Web应用程序。在该应用程序中,我需要在表单的body-onload事件之前执行一些java脚本。

Html标记

<body onload="ShowWait();">
   ......
</body>

我在ShowWait();上运行body-onload。 此脚本显示请等待窗口。 但我需要在此事件之前运行此代码。 是否有任何事件可以帮助我在页面加载之前运行脚本。

4 个答案:

答案 0 :(得分:3)

鉴于该函数被称为ShowWait(),您不需要“需要在页面加载之前运行JavaScript”,但是您希望“显示加载屏幕直到页面加载了“

只需将加载元素放入HTML中,然后在页面加载后使用JavaScript将其删除。

答案 1 :(得分:0)

将head标记放在head元素中,并附带要运行的脚本

答案 2 :(得分:0)

为什么不把这一行放在脚本标签中作为你身体的第一行呢?它将作为第一件事运行。

答案 3 :(得分:-1)

如果您将Javascript语句(而不是函数定义)放在标记内,它们将在页面加载期间执行 - 在onLoad事件被触发之前。

<html>
 <body>
   <h2>First header</h2>
   <script type="text/javascript">
     alert("Hi, I am here"); 
     document.write("<h3>This is Javascript generated</h3>");
   </script>
   <h2>Second header</h2>
 </body>
 </html>

需要注意的是,您无法按ID搜索元素,因为这些元素可能尚未呈现,因此您以此方式更改页面的能力有限。

底线:可能,不推荐。

在这种情况下我通常做的如下:

Make the parts of the page that may change invisible (via style="visibility:hidden;");
Make onLoad run a Javascript code that changes the page and then sets the visibility of the said parts to visibility:visible.