1. innerHTML的問題
使用innerHTML插入<script>標簽,其中的js文件是不會加載的,
document.getElementById('div1').innerHTML = `
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
`;
雖然DOM中有了這些節(jié)點,但是js文件還是沒有加載,更沒有被調用,
<div id="div1">
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
</div>
我們在控制臺實驗一下:
> window.jQuery
undefined
MDN中,對innerHTML的解釋如下,
const name = "<script>alert('I am John in an annoying alert!')</script>";
el.innerHTML = name; // harmless in this case
Although this may look like a cross-site scripting attack, the result is harmless. HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
2. 動態(tài)創(chuàng)建
我們可以動態(tài)創(chuàng)建script元素,將它插入DOM中,來加載js文件,
const install = ({ src, success }) => {
const script = document.createElement('script');
script.src = src;
script.async = false; // 默認值為true
script.onload = success;
const head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
例子:
install({
src: '//code.jquery.com/jquery-3.2.1.min.js'
});
install({
src: './1.js' // 內容為:alert(window.jQuery);
});
其中,script.async默認值為true,表示加載的js文件會異步執(zhí)行,
MDN中,對async的解釋如下,
async
A boolean attribute indicating that the browser should, if possible, execute the script asynchronously. This attribute must not be used if the src attribute is absent (i.e. for inline scripts). If it is included in this case it will have no effect. Dynamically inserted scripts execute asynchronously by default, so to turn on synchronous execution (i.e. scripts execute in the order they were loaded) setasync=false.
如果設置了script.async = false;,
1.js會彈出提示function function(a,b){return new r.fn.init(a,b)},
否則,在默認情況下,script.async為true,
1.js會彈出提示undefined。
參考
MDN: Element.innerHTML - Security considerations
MDN: <script> - async