有线道场/ domReady!行为

时间:2017-03-27 20:04:10

标签: javascript html dojo

我正在学习Dojo Toolkit并遇到有关dojo/domReady!的有线问题。我有一个工作的例子:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Tutorial: Hello Dojo!</title>
    <!-- load Dojo -->
    <script>
        var dojoConfig = {
            async: true,
        };
    </script>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>
</head>
<body>
    <script>
        require([
            'dojo/dom',
            'dojo/dom-construct',
            'dojo/domReady!'
        ], function (dom, domConstruct) {
            var greetingNode = dom.byId('greeting');
            domConstruct.place('<em> Dojo!</em>', greetingNode);
        });
    </script>
    <!-- <script src="./script.js"></script> -->
    <h1 id="greeting">Hello</h1>
</body>
</html>

但是,如果我将javascript代码移动到外部文件中并在<h1 id...</h1>之前将其提取,则无效。 (这很奇怪,代码在StackOverflow的页内HTML编辑器中工作!)

require([
    'dojo/dom',
    'dojo/dom-construct',
    'dojo/domReady!'
], function (dom, domConstruct) {
    var greetingNode = dom.byId('greeting');
    domConstruct.place('<em> Dojo!</em>', greetingNode);
});
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Tutorial: Hello Dojo!</title>
    <!-- load Dojo -->
    <script>
        var dojoConfig = {
            async: true,
        };
    </script>
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>
</head>
<body>
    <script src="./script.js"></script> <!-- this position is not OK in my local machine-->
    <h1 id="greeting">Hello</h1>
    <!-- <script src="./script.js"></script> --> <!-- this position is OK-->
</body>
</html>

但它实际上无法在我的本地计算机上运行,​​请参阅屏幕截图: enter image description here任何人都可以帮我这个吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您应该在HTML文件的头部移动以下代码:

<script>
    require([
        'dojo/dom',
        'dojo/dom-construct',
        'dojo/domReady!'
    ], function (dom, domConstruct) {
        var greetingNode = dom.byId('greeting');
        domConstruct.place('<em> Dojo!</em>', greetingNode);
    });
</script>

之后
 <script>
        var dojoConfig = {
            async: true,
        };
    </script>

基本上dojo/domReady!将等到DOM完成加载后再返回,并且IMO不是按照你问题中描述的方式使用的。