[FE] 如何動態(tài)加載js文件

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) set async=false.

如果設置了script.async = false;,
1.js會彈出提示function function(a,b){return new r.fn.init(a,b)},

否則,在默認情況下,script.asynctrue,
1.js會彈出提示undefined


參考

MDN: Element.innerHTML - Security considerations
MDN: <script> - async

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,991評論 0 0
  • =========================================================...
    lavor閱讀 3,645評論 0 5
  • 瀏覽器中script標簽加載順序是如何的呢?這個問題折騰了好幾次了,之前弄清楚了以后,覺得做不做筆記的無關緊要,可...
    世事如煙_f411閱讀 1,704評論 0 1
  • 我不知道這一生還會遇到多少人,還會真的愿意接受哪些人,這段時間來,莫名的恐懼總是涌上心頭,特別是一個人獨處的時候,...
    可愛的兔子呀閱讀 279評論 0 0
  • 五月,我們有兩種身份,一種是學生,一種是社會人士; 五月,我們有兩種選擇,一種是深造,一種是淡出;五月,宿舍內燈火...
    成長路閱讀 251評論 0 0

友情鏈接更多精彩內容