请查看GWT.runAsync
下面的Google I/O演讲,其中JavaScript
涉及GWT
项目的延迟加载.
我想这就是您正在寻找的。
<body onload="onloadHandler();">
<script type="text/javascript">
function onloadHandler() {
if (document.createElement && document.getElementsByTagName) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = './test.js';
var heads = document.getElementsByTagName('head');
if (heads && heads[0]) {
heads[0].appendChild(script);
}
}
}
function iAmReady(theName) {
if ('undefined' != typeof window[theName]) {
window[theName]();
}
}
function test() {
// stuff to do when test.js loads
}
</script>
Run Code Online (Sandbox Code Playgroud)
-- 测试.js
iAmReady('test');
Run Code Online (Sandbox Code Playgroud)
已在 Firefox 2、适用于 Windows 的 Safari 3.1.2、IE 6 和 Opera 9.52 中测试并运行。我认为这些的高级版本也应该可以工作。
请注意,加载是异步的。如果您在调用后立即尝试在加载的文件中使用函数或变量,appendChild()
它很可能会失败,这就是为什么我在加载的脚本文件中包含一个回调,该回调强制在脚本加载完成时运行初始化函数。
您还可以在加载的脚本底部调用内部函数来在加载脚本后执行某些操作。