3

I'm playing around with Kinetic.js and I noticed that only linking my javascript at the end of the body would work. Normally wouldn't adding javascript in the head would work?

Here is my HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Tictactoe</title>
        <META http-equiv="Content-Script-Type" content="type">
    </head>

    <body>
        <div id="container"></div>
        <script type="text/javascript" src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.4.0.min.js"></script>
        <script type="text/javascript" src="javascript.js"></script>
    </body>
</html>

And here is my javascript file:

var stage = new Kinetic.Stage({
    container: 'container',
    width: 500,
    height: 500
});

var layer = new Kinetic.Layer();

var rect = new Kinetic.Rect({
    x: 239,
    y: 75,
    width: 150,
    height: 50,
    fill: 'green',
    stroke: 'black',
    strokeWidth: 4
});

// add the shape to the layer
layer.add(rect);

stage.add(layer);
4

6 回答 6

2

The DOM isn't ready when your code is run if you reference it in the head of the page. When Kinetic tries to access your container div it isn't available. If you check the console you'll probably see an error.

Including your script in the bottom of the page guarantees that the DOM is available when the code runs. See this stackoverflow thread for a full explanation.

It's perfectly acceptable to use the approach you're using. See the HTML5 Boilerplate which uses the same technique. Or if you're set on including your script in the head, you could use jQuery's document ready event which won't fire until the DOM is rendered.

于 2013-04-04T23:34:13.860 回答
2

It is because it has to load the HTML Element before it runs. Try using the "onload()" function to fix this.

于 2013-04-04T23:35:13.053 回答
2

在不了解这个kinetic库的情况下,我的猜测是它不会等待页面加载来采取任何行动。因此,如果您在页面顶部包含 JS 文件,那么您container还没有在 DOM 中。

于 2013-04-04T23:35:17.393 回答
2

可能脚本正在尝试使用 DOMELement。因此,如果您的脚本位于 HEAD 中,则尚未加载 BODY 标签。如果您将脚本放在 BODY 的末尾,则 BODY 内容已经加载..

因此,如果您真的想在 HEAD 上加载,您应该将脚本附加到 body.onloaded 事件上。

于 2013-04-04T23:35:22.133 回答
1

尝试这个:

window.onload=function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 500,
height: 500
});
var layer = new Kinetic.Layer();

var rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 150,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4  
});

// add the shape to the layer
layer.add(rect);

stage.add(layer);
}
于 2013-04-04T23:38:38.393 回答
1

您很可能遇到了一个问题,即 DOM 尚未准备好,但您的脚本已经在尝试与元素交互。

这就是为什么当脚本被添加到 body 标记的底部时,它会在添加元素后加载它。

而不是将脚本标签添加到正文标签,您应该将代码包装在 的onload事件中,window以确保它仅在 DOM 准备好后执行。

与此类似:

window.onload = function(){
    // ... your code here
}

上面将设置一个在窗口的加载事件触发时调用的函数。
如果您需要在不同的 JavaScript 文件中将多个函数添加到事件中,您也可以类似下面的方式编写它:

window.addEventListener('onload', function(){
    // ... your code here
})

load 事件在文档加载过程结束时触发。至此,文档中的所有对象都在 DOM 中,所有图片和子帧都加载完毕。

于 2013-04-04T23:38:44.287 回答