【发布时间】:2014-01-24 16:40:32
【问题描述】:
我正在处理一个仅在页面的<body> 中使用<canvas> 的简单页面。所有内容都将通过javascript加载。我在我的 javascript 中使用该文档时遇到了问题,我想知道是否有人可以指出我使用 <script> 标签的正确方向。这是我的主要问题:
- 对于使用 window.onload 加载的函数,
<script>的适当位置是什么
这是我正在使用的代码:
index.html
----
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="window.js" type="text/javascript"></script>
</head>
<body>
<canvas>Canvas is not supported by your browser!</canvas>
</body>
window.js
----
Window = function(doc, win)
{
this.doc = doc;
this.win = win;
this.initialize();
}
Window.prototype =
{
initialize: function()
{
this.doc.documentElement.style.overflow = 'hidden';
this.doc.body.scroll = "no";
this.resize();
this.win.addEventListener('resize', this.resize.bind(this));
},
resize: function()
{
_canvas = this.doc.querySelector('canvas');
_canvas.width = this.win.innerWidth;
_canvas.height = this.win.innerHeight;
}
};
window.onload = new Window(document, window);
在我运行过的这个脚本的所有测试中,它工作的唯一实例是<script> 放在初始<body> 标记之后。当我将<script> 放在<head> 中时,它给了我一个错误提示:
Uncaught TypeError: Cannot set property 'value' of null
为了一个看起来干净的文档,<script> 不可能出现在<head> 中吗?
任何关于正确做法的澄清或指导将不胜感激!
【问题讨论】:
-
脚本应始终加载到 中。您遇到的情况可能是由于您的脚本在整个页面呈现之前运行。
-
@Diodeus 这是不对的!主要是不管脚本包含在哪里。最快的执行是在
body标记的末尾。 -
阅读此答案以获取有关脚本放置的更多信息:stackoverflow.com/a/4396937/1310604
标签: javascript html dom