Javascript 加载前的Javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7136705/
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-24 00:59:56  来源:igfitidea点击:

Javascript before onload?

javascriptonload

提问by NoBugs

Is there any event handler before onLoad/onPageShow? The trouble with onLoad is if there is any change in display, the page will show up without change until it is fully loaded, then the script will run. What is the best way to make sure it will run as soon as possible?

在 onLoad/onPageShow 之前是否有任何事件处理程序?onLoad 的问题是如果显示有任何变化,页面将无变化地显示,直到完全加载,然后脚本才会运行。确保它尽快运行的最佳方法是什么?

回答by Itay Maman

If you put Javascript statements(rather than function definitions) inside a <script>tag, they will be executed during page loading - before the onLoad event is fired.

如果您将 Javascript语句(而不是函数定义)放在<script>标签中,它们将在页面加载期间执行 - 在 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>

The caveat is that you cannot search for elements by ID because these element might not have been rendered yet, so your ability to change the page that way is limited.

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

Bottom line: possible, not recommended.

底线:可能,不推荐。

What I usually do in such situations is as follows:

在这种情况下,我通常会做以下事情:

  • 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.
  • 使页面中可能发生变化的部分不可见(通过style="visibility:hidden;");
  • 让 onLoad 运行改变页面的 Javascript 代码,然后将所述部分的可见性设置为visibility:visible.

回答by Paul Fabing

The simple answer is to place the function call after the DOM element inside script tags, within the body of your page. I had this problem using a javascript function to style my navigation menu links, however I had a google map element that caused the page to load slowly. On this paticular page, I ran the script just after the link. It is a solution, maybe not the best but it works. Hope this helps.

简单的答案是将函数调用放在脚本标签内的 DOM 元素之后,在您的页面正文中。我使用 javascript 函数来设置导航菜单链接的样式时遇到了这个问题,但是我有一个导致页面加载缓慢的谷歌地图元素。在这个特定的页面上,我在链接之后运行了脚本。这是一个解决方案,也许不是最好的,但它有效。希望这可以帮助。