$(document).on()不是在加载$ .getScript()的脚本中执行的

时间:2016-02-12 07:28:06

标签: jquery

在$(document).on()里面我通过$ .getScript()加载一个外部js文件,加载的文件又有一个永远不会执行的$(document).on()方法。为什么会这样? 我使用jquery 1.12.0。

<file1.js>
var event = new Event('app_Ready');
document.dispatchEvent(event);
$(document).on("app_Ready", function() {
   alert("app_Ready ok file1");//this works ok
   $.getScript("file2.js");
}

<file2.js>
$(document).on("app_Ready", function() {
   alert("app_Ready ok file2");//this doesnt work
});

1 个答案:

答案 0 :(得分:0)

file2.js中的代码仅在文件加载后触发app_Ready事件时执行。尝试在$.getScript的回调函数中执行此操作。

$.getScript("file2.js", function() {
    document.dispatchEvent(event);
});

或者你可以摆脱$(document).on()中的file2.js,并立即运行代码。目前尚不清楚为什么需要它,因为文件直到事件发生后才加载。