创建script元素
var script = document.createElement('script');
document.head.appendChild(script); // insert into the <head></head> tag
script.addEventListener('load', ev => { // when the js execute done
// ...
});
script.src = '/foo.js'; // start execute a js, can delay
示例
index.tsx
import './index.html';
import * as ReactDOM from 'react-dom';
import ohMyJs from '!file-loader!./oh~my~js.js';
ReactDOM.render((
<div>
<h1 id="load">未加载JS</h1>
<button onClick={() => {
var script = document.createElement('script');
document.head.appendChild(script);
script.addEventListener('load', (ev) => {
document.getElementById('load').innerText = `计算完毕,F(${window.MAX}) = ${window.FMAX}`;
});
setTimeout(() => {
script.src = ohMyJs;
document.getElementById('load').innerText = '脚本执行中';
}, 200); // 可以超时设置src,但仅第一次赋值有效
}}>
动态加载JS,计算斐波拉契数列
</button>
</div>
), /* container */ document.querySelector('#app'));
oh~my~js.js
console.log('on~my~js 加载中');
function F(n) {
if (n < 2) return 1;
return F(n - 1) + F(n - 2);
}
window.MAX = 42;
for (var i = 0; i < MAX; i++) {
console.log(i, window.FMAX = F(i));
}
console.log('on~my~js 加载完毕');
通用解决方案
/**
* 动态注入脚本,并监听执行完毕事件
* @param {string} src
* @param {() => void} onload
*/
function injectJS(src, onload) {
var loaded = Array.from(document.scripts).some(it => it.getAttribute('src') === src); // Warn:script.src !== script.getAttribute('src')
if (loaded) {
typeof onload === 'function' && onload();
return;
}
var script = document.createElement('script');
script.src = src;
document.head.insertBefore(script, document.head.firstElementChild);
script.addEventListener('load', (ev) => {
typeof onload === 'function' && onload();
});
}
END