3

私はこのコードを持っています:

$(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 の変数にアクセスしようとすると、window.load の後に file.js スクリプトが読み込まれるように見えるため、問題が発生します。file.js が読み込まれるまで待つにはどうすればよいですか? または、このコードを整理するより良い方法はありますか?

4

3 に答える 3

2

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." );
});
于 2013-07-22T19:32:32.817 に答える
1

$(window).load();代わりに使用してください$(document).ready()。詳細については、こちらを参照してください。

于 2013-07-21T22:00:29.943 に答える