如何在页面加载之前运行 JavaScript 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6944037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:53:27  来源:igfitidea点击:

How to run JavaScript code before page load?

javascriptjqueryasp.net

提问by Yashwant Kumar Sahu

I have working in asp.netweb application. Here I need to run JavaScriptbefore page load.

我在asp.netweb 应用程序中工作。这里我需要在页面加载之前运行JavaScript

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.

这里只有 funload() 正在工作。

回答by Pushpendra

You can use window.onpaint for such purpose like :

您可以将 window.onpaint 用于以下目的:

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

I hope it helps you....

我希望它能帮助你......

回答by TJHeuvel

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.

或者把它放在一个函数中并立即调用它。尝试将它放在页面的最顶部,但是由于 DOM 尚未加载,因此您无法获得任何其他元素。

What is it you want to do?

你想做什么?

回答by Einacio

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

只需在您希望它运行的正文中的任何位置插入一个 <script> 标记。只要解析器读取它,它就会立即执行,只要它不引用尚未创建的元素

回答by Safran Ali

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

尝试将您的脚本放在页面的 head 部分:

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

回答by Madhur Ahuja

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

为什么不使用ClientScriptManager.RegisterClientScriptBlock Methodhttp://msdn.microsoft.com/en-us/library/btf44dc9.aspx