javascript - 关闭 - 库未正确加载

标签 javascript loading require google-closure

我的开发环境中有一个运行良好的 Closure 环境。但是,在新的文件夹和文件中,它不起作用。

例如,拿这个测试脚本:

goog.require('goog.dom');
console.log(goog);
console.log(goog.dom);
goog.dom.getElement('logout').innerHTML = "Heck";

就是这样,加上 HTML 中的 base.js

第一个 console.log 显示了一个包含所有正确内容的对象。所有文件也都加载到 DOM 中。

然而,第二个控制台日志显示 undefined 因此最后一行不起作用(很明显)。 Chrome 控制台错误是 Uncaught TypeError: Cannot call method 'getElement' of undefined

这到底是怎么回事?如果我尝试 XhrIo 也是一样的。它没有在 goog 对象上找到方法。

谢谢。

最佳答案

Documentation:

Note: Do not put your goog.require() statements in the same script tag as the entry point to code that uses the goog.required functions or classes. A goog.require() call adds code to the document after the script tag containing the call.

所以

<script>
    goog.require('goog.dom');
    console.log(goog.dom);
</script>

打印未定义。但是

<script>
    goog.require('goog.dom');
</script>
<script>
    console.log(goog.dom);
</script>

<script>
    goog.require('goog.dom');
    addEventListener('load', function() {
        console.log(goog.dom);
    });
</script>

打印一个对象。

仅供引用,还有其他可能的工作流程。例如,closurebuilder.py 脚本可以帮助提前加载所有需要的文件。

关于javascript - 关闭 - 库未正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561866/

相关文章:

javascript - 是否可以记住文件上传字段中的文件名,然后通过 javascript 启动该文件?

javascript - 通过索引验证元素的存在

javascript - IDBDatabase.transaction 始终为 null

javascript - Jquery 延迟来自每个循环的 ajax 请求

android - picasso 不加载图像

javascript - 使用 pace.js 加载时隐藏页面

php - 网页仍在加载 - 检查它正在等待什么

javascript - 我正在与 requirejs 优化器和非 AMD 模块作斗争

node.js:为什么 NODE_DEBUG=1 不起作用? (试图调试 require() 错误)

javascript - 两个变量在 Node.js 中使用 require (引用问题)引用相同的 config.js 文件