JavaScript放在HTML页面上的位置是否重要? [英] Does it matter where JavaScript is placed on a html page?

查看:60
本文介绍了JavaScript放在HTML页面上的位置是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搞乱了html5,我以前从来没有真正好好看过JavaScript。
我正在引用这样的脚本文件(不在脑中)

I've messing about with html5, I've never really had a good look at JavaScript before. I'm referencing script file like this (not in the head)

<script src="somthing.js"></script>

但是,如果脚本放在页面上的某些元素下面,它似乎只能起作用。

However the script only seems to work if it placed below certain elements on the page.

在javascript放置的地方是否有特殊情况?

Are there particular situations when it matters where javascript is placed?

提前致谢。

推荐答案

如果脚本没有等待 onload 或就绪事件某种,它需要在它引用的元素之后放置 (否则它们不会在那里找到)。如果您不确定,请在< / body> 之前坚持下去。

If the script isn't waiting for an onload or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>.

在这种情况下看起来像这正是发生的事情,它正在寻找尚未添加到DOM的元素。将脚本放在< body> 的底部是解决此问题的常见做法。一些替代方法是使用 window.onload 事件来运行代码,或使用jQuery的 $(文档).ready()例如(大多数主要图书馆都有相同的一些)。

In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body> is one common practice to counter this. Some alternatives are using the window.onload event to run your code, or jQuery's $(document).ready() for example (most major libraries have some equivalent of this).

这篇关于JavaScript放在HTML页面上的位置是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆