2012-02-24 21 views
2

次のコードスニペットを使用して、非ブロッキングの方法でJavaScriptを非同期に読み込みます。 Chrome、FFでも動作しますが、Internet Explorerでは動作しません。インターネットエクスプローラーで匿名関数が機能しない

私はIE8を実行しており、以下のコードではIEのonload関数にヒットできません。

  <script type="text/javascript"> 
      (function() { 
       var s = document.createElement('script'); 
       s.type = 'text/javascript'; 
       s.async = true; 
       s.src = 'js/load_outer.js'; 
       s.onload = function() { 
        alert("Loaded"); 
       } 

       var x = document.getElementsByTagName('script')[0]; 
       x.parentNode.insertBefore(s, x); 
      })(); 
     </script> 

誰かが間違いを特定するのに手伝ってください。

おかげ

+0

あなたは、または「ロード」イベントを取得できない場合がありますと、スクリプトのロードIEで。 – Pointy

+0

関連する質問があります:[http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer](http://stackoverflow.com/questions/4845762/onload- script-handler-for-script-tag-in-internet-explorer)を使用します。 – jabclab

+0

@jakeclarksonリンクをありがとう。しかし、私はサードパーティライブラリ – Jayesh

答えて

2

IE(9より前の)代わりにonreadystatechangeを使用し、<script>要素のonloadイベントをサポートしていません:

var complete = false; 
script.onload = script.onreadystatechange = function() { 
    if (!complete && (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) { 
     complete = true; 
     // your callback code here 
    } 
} 
+1

の使用を避けなければなりませんでした。これは助けになりました。私はIE9で同様の問題に立ち往生した。それはダブルコールバックを与えます。ここでそれを解決する記事があります - http://www.aaronpeters.nl/blog/prevent-double-callback-execution-in-IE9 – Jayesh