如何等待附加到正文的 <script> 完成执行

当用户单击按钮时,我需要将外部脚本附加到我的正文中。这是要求。


菜鸟问题。假设外部库创建了一个 window.newLib 变量。当 newLib 变量可供我使用时,如何通知我?


我尝试了这个,但 onload 没有被调用:


  const script = document.createElement('script');

  script.innerHTML = 'window.test = 1; console.log("test defined.");';

  script.onload = "console.log('onload called.', window.test)"

  script.async = false;

  document.body.appendChild(script);

这可行,但对我来说似乎很脏。有没有更好的办法?


const injectScript = () => {

  const script = document.createElement('script');

  script.innerHTML = 'setTimeout(() => {window.test = 1},10500); console.log("test defined.");';

  script.async = false;

  document.body.appendChild(script);

}


const nap = ms => new Promise(res => setTimeout(res, ms));


const maxAttempts = 100;

const msNap = 100; // 10s timeout


const start = async () => {

  injectScript();

  let id = 0;

  while (true) {

    if (++id === maxAttempts) {

      throw(`Lib took too long to load: ${id * msNap}ms`);

    }

    if (window.test) break;

    await nap(msNap);

  }

  console.log('External lib correctly loaded.');

};

start();


largeQ
浏览 128回答 2
2回答

吃鸡游戏

这似乎按预期工作:const script = document.createElement('script');script.src = 'data:text/html,id = 0;while(true){ if(++id==1000000) break;} window.test = 1; console.log("test defined.");';script.onload = () => console.log('onload called.', window.test);document.body.appendChild(script);

慕村225694

尝试这个:const injectScript = () => {&nbsp; &nbsp; &nbsp; &nbsp; const script = document.createElement('script');&nbsp; &nbsp; &nbsp; &nbsp; script.innerHTML = 'console.log("Function loaded..."); window.postMessage({cmd:"loaded"});';&nbsp; &nbsp; &nbsp; &nbsp; script.async = false;&nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(script);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; setTimeout(injectScript, 3000);&nbsp; &nbsp; &nbsp; &nbsp; window.addEventListener('message', function(e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(e.data.cmd === 'loaded'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('external library loaded');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5