让IE等待从外部资源加载babel-polyfill

时间:2018-08-19 03:52:32

标签: javascript internet-explorer babel babel-polyfill

我只需要为IE加载 babel-polyfill 。另外,还需要让IE等待并且不要执行console.log('Checkpoint 2');及其下面的代码(包括 IeOnlyPolyfillTest.js ),直到从以下位置完全加载 babel-polyfill 外部资源。

 <body>
  <script type="text/javascript">

    var userAgent = window.navigator.userAgent;
    var isInternetExplorer = userAgent.indexOf('Trident/') > 0 || userAgent.indexOf('MSIE ') > 0;

    if (isInternetExplorer) {
      var htmlDocumentHead = document.getElementsByTagName('head')[0];
      var babelPolyfillScript = document.createElement('script');
      babelPolyfillScript.type = 'text/javascript';
      babelPolyfillScript.src = 'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.0.0-rc.1/polyfill.min.js';
      console.log('Checkpoint 1');
      htmlDocumentHead.appendChild(babelPolyfillScript);
      console.log('Checkpoint 2');
    }

  </script>
  <script type="text/javascript" src="scripts/IeOnlyPolyfillTest.js"></script>
</body>  

IeOnlyPolyfillTest.js 部分:

(function launchApplication() {
  console.log('Checkpoint 3');
  testSymbolFeature();
})();

function testSymbolFeature() {
  let symbolTest = Symbol('foo');
  console.log(`Symbol feature is working! ${symbolTest.toString()}`);
}

首先,我无法添加async="false"属性:

babelPolyfillScript.async = false; // no effect
babelPolyfillScript.async = 'false'; // async="" will be generated

我尝试了以下解决方案(original answer):

var script = document.createElement("script");
script.src = "script.js";
console.log("a");
document.body.appendChild(script);
console.log("b");

就我而言,日志顺序也总是正确的,但是,如果重新加载页面几次,我们会随机获取有错误的案例和无错误的案例(换句话说,错误情况尚不清楚,并且会逐例发生):

坏情况:

enter image description here

好的情况:

enter image description here

那么,我们该怎么做才能使console.log('Checkpoint 2');和下面的所有脚本等到 babel-polyfill 完全加载?

0 个答案:

没有答案