-
友情链接:
Powered by 东森娱乐平台登录注册 @2013-2022 RSS地图 HTML地图
脚本注入默认是异步注入的,异步并行注入,两个 <script> 标签是几乎同时插入 <body>, 浏览器不会保证先插入的脚本先执行完,这就可能导致:第二个脚本执行时,第一个脚本还 没加载或还未定义其函数;于是如果第二个脚本需要调用第一个脚本里的函数就会报错:除非注入后不remove移除,比如:
const scriptElement = document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = chrome.runtime.getURL(file);
bodyElement.appendChild(scriptElement);
否则,就需要按顺序注入,比如:
if (!bodyElement) return;
const loadNext = (index) => {
if (index >= files.length) return;
const file = 'scripts/' + files[index] + '.js';
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = chrome.runtime.getURL(file);
script.onload = () => {
script.remove(); // 可选清理
loadNext(index + 1); // 加载下一个
};
script.onerror = (err) => console.error(`加载失败: ${file}`, err);
bodyElement.appendChild(script);
};
loadNext(0); // 从第一个开始加载
Powered by 东森娱乐平台登录注册 @2013-2022 RSS地图 HTML地图