[英]How to run JavaScript code as soon <body> element is defined?
Here is my code: 这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Foo</title>
</head>
<body>
<script>
console.log('test')
</script>
<p>
Foo
</p>
</body>
</html>
I want to move the JavaScript in this code from <body>
into <head>
. 我想将此代码中的JavaScript从<body>
到<head>
。 Here is my incorrect attempt: 这是我不正确的尝试:
<!DOCTYPE html>
<html>
<head>
<title>Foo</title>
<script>
window.onload = function () {
console.log('test')
}
</script>
</head>
<body>
<p>
Foo
</p>
</body>
</html>
This of course does not do what I want. 这当然不符合我的要求。 It runs the JavaScript only after the whole page has loaded. 它只在整个页面加载后运行JavaScript。 But I want the JavaScript to run as soon as <body>
is defined. 但是我想在定义<body>
立即运行JavaScript。 Can this be done in JavaScript? 可以用JavaScript完成吗?
Insert your log command into a defined Javascript function at the <head>
part of your Html and call this function soon after the opening of <body>
. 将您的日志命令插入到Html的<head>
部分的已定义的Javascript函数中,并在打开<body>
后立即调用此函数。
Your final code will look this way: 你的最终代码将是这样的:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(){
console.log('test');
}
</script>
<title>Foo</title>
</head>
<body>
<script>
myFunction();
</script>
<p>
Foo
</p>
</body>
</html>
It's worth to mention that the onload event-property do exists in another html tags too, and only on those cases it is executed right after it's definition, which means: immediately. 值得一提的是, onload事件属性确实存在于另一个html标签中,并且只有在这些情况下它才会在定义后立即执行,这意味着:立即执行。
With <body>
tag happens something singular: the onload only runs after two conditions: 使用<body>
标签发生奇异的事情: onload仅在两个条件之后运行:
1) the express definition of </body>
; 1) </body>
的明确定义;
2) the finishing of the loading of all accessory and maybe external routines and resources, which means: the loading of all html, css, jpg, gif, svg etc. 2)完成所有附件的加载以及可能的外部例程和资源,这意味着:加载所有html,css,jpg,gif,svg等。
So, the onload do what it promises: runs when and only after page 100% loaded. 因此, onload执行它所承诺的内容: 在页面100%加载时运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.