我有这个代码:

$(document).ready(function() {
    window.addEventListener('DOMContentLoaded', function() {
    var s = d.createElement('script');
    s.async = false;
    s.src = 'file.js';
    s.id = 'script';
    d.body.appendChild(s);
    });
});

$(window).load(function() {
    workwithvariablesInfilejs();
});

似乎 document.ready 首先触发,然后 window.load 触发。但是如果尝试访问 file.js 的变量,我会遇到麻烦,因为 file.js 脚本似乎是在 window.load 之后加载的。我怎样才能等到 file.js 被加载?或者有没有更好的方法来组织这段代码?

最佳答案

你可以使用 getscript 方法:http://api.jquery.com/jQuery.getScript/
然后在“.done”回调中调用“workwithvariablesInfilejs()”。

$.getScript("file.js")
.done(function(script, textStatus) {
  console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
  $( "div.log" ).text( "Triggered ajaxError handler." );
});

关于javascript - 脚本加载完成后如何开始执行代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17777340/

10-12 00:03
查看更多