当用户单击按钮时,我需要将外部脚本附加到我的正文中。这是要求。
菜鸟问题。假设外部库创建了一个 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();
吃鸡游戏
慕村225694
相关分类