創(chuàng)建script元素并添加到DOM可動(dòng)態(tài)加載JavaScript文件;2. 使用Promise封裝可實(shí)現(xiàn)更簡(jiǎn)潔的異步控制;3. 需注意執(zhí)行順序、CORS、安全風(fēng)險(xiǎn)及重復(fù)加載問(wèn)題;4. 可通過(guò)Set記錄已加載腳本防止重復(fù)加載。該方法適用于懶加載、第三方組件或條件性功能,且必須確保腳本來(lái)源可信,最終通過(guò)onload或onerror回調(diào)處理結(jié)果,整個(gè)過(guò)程由瀏覽器自動(dòng)完成腳本的下載與執(zhí)行。
You dynamically load a JavaScript file in the browser by creating a <script></script>
element using JavaScript and appending it to the DOM. This allows you to load and execute a script on demand, rather than including it statically in your HTML.

Here’s how to do it:
1. Using document.createElement('script')
This is the most common and straightforward method.

function loadScript(src, callback) { const script = document.createElement('script'); script.src = src; // Optional: Run code when the script is loaded script.onload = function() { console.log('Script loaded successfully:', src); if (callback) callback(null, script); }; // Optional: Handle loading errors script.onerror = function() { console.error('Failed to load script:', src); if (callback) callback(new Error(`Failed to load ${src}`)); }; // Append the script to the document (usually <head> or <body>) document.head.appendChild(script); } // Usage: loadScript('https://example.com/external-script.js', function(err, script) { if (err) { console.error('Script load error:', err); } else { console.log('External script executed.'); } });
2. Promisified Version (Modern Approach)
For cleaner async handling, wrap it in a Promise:
function loadScriptAsync(src) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = src; script.onload = () => resolve(script); script.onerror = () => reject(new Error(`Failed to load ${src}`)); document.head.appendChild(script); }); } // Usage with async/await: async function init() { try { await loadScriptAsync('/path/to/script1.js'); await loadScriptAsync('/path/to/script2.js'); console.log('All scripts loaded'); } catch (err) { console.error('Error loading script:', err); } }
3. Important Notes
- Execution Timing: The loaded script executes as soon as it's downloaded, so make sure any dependencies are loaded in the right order.
- CORS: If loading from another domain, the server must allow it via CORS headers.
- Security: Only load scripts from trusted sources—dynamically injecting scripts can be a security risk (XSS).
- Duplicate Loading: The browser may cache the script, but if you want to prevent reloading, you can track which scripts are already loaded.
4. Preventing Duplicate Loads
const loadedScripts = new Set(); function loadScriptOnce(src, callback) { if (loadedScripts.has(src)) { if (callback) callback(null); return; } const script = document.createElement('script'); script.src = src; script.onload = () => { loadedScripts.add(src); if (callback) callback(null); }; script.onerror = () => callback(new Error(`Failed to load ${src}`)); document.head.appendChild(script); }
This ensures a script isn’t loaded twice.

Basically, dynamically loading JavaScript is just about creating a script tag and letting the browser handle the rest. It's simple but powerful for lazy-loading features, third-party widgets, or conditional functionality.
以上是您如何動(dòng)態(tài)加載JavaScript文件?的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

Python實(shí)現(xiàn)無(wú)頭瀏覽器采集應(yīng)用的頁(yè)面動(dòng)態(tài)加載與異步請(qǐng)求處理功能解析在網(wǎng)絡(luò)爬蟲(chóng)中,有時(shí)候需要采集使用了動(dòng)態(tài)加載或者異步請(qǐng)求的頁(yè)面內(nèi)容。傳統(tǒng)的爬蟲(chóng)工具對(duì)于這類頁(yè)面的處理存在一定的局限性,無(wú)法準(zhǔn)確獲取到頁(yè)面上通過(guò)JavaScript生成的內(nèi)容。而使用無(wú)頭瀏覽器則可以解決這個(gè)問(wèn)題。本文將介紹如何使用Python實(shí)現(xiàn)無(wú)頭瀏覽器來(lái)采集使用動(dòng)態(tài)加載與異步請(qǐng)求的頁(yè)面內(nèi)容

Vue中處理組件的動(dòng)態(tài)加載和切換Vue是一個(gè)流行的JavaScript框架,它提供了各種靈活的功能來(lái)處理組件的動(dòng)態(tài)加載和切換。在本文中,我們將討論一些Vue中處理組件動(dòng)態(tài)加載和切換的方法,并提供具體的代碼示例。動(dòng)態(tài)加載組件是指根據(jù)需要在運(yùn)行時(shí)動(dòng)態(tài)加載組件。這樣可以提高應(yīng)用程序的性能和加載速度,因?yàn)橹挥挟?dāng)需要時(shí)才會(huì)加載相關(guān)的組件。Vue提供了async和awa

如何使用Vue和Element-UI創(chuàng)建動(dòng)態(tài)加載數(shù)據(jù)的表格在現(xiàn)代的Web開(kāi)發(fā)中,數(shù)據(jù)表格是常見(jiàn)的界面組件之一。Vue.js是當(dāng)下非常流行的前端框架,而Element-UI是基于Vue.js開(kāi)發(fā)的一套組件庫(kù),提供了豐富的UI組件供我們使用。本文將介紹如何使用Vue和Element-UI來(lái)創(chuàng)建一個(gè)可以動(dòng)態(tài)加載數(shù)據(jù)的表格,并且給出相應(yīng)的代碼示例。首先,我們需要安裝

Golang熱更新原理探究:動(dòng)態(tài)加載與重載的奧秘引言:在軟件開(kāi)發(fā)領(lǐng)域,程序員們經(jīng)常希望能夠在不重啟應(yīng)用的情況下進(jìn)行代碼修改和更新。這樣的需求對(duì)于開(kāi)發(fā)效率和系統(tǒng)運(yùn)行的可靠性都具有重要意義。而Golang作為一門現(xiàn)代化的編程語(yǔ)言,為開(kāi)發(fā)者提供了許多便捷的機(jī)制來(lái)實(shí)現(xiàn)熱更新。本文將深入探討Golang熱更新的原理,特別是動(dòng)態(tài)加載和重載的奧秘,并將結(jié)合具體的代碼示例進(jìn)

解決Vue報(bào)錯(cuò):無(wú)法正確使用VueRouter根據(jù)路由參數(shù)動(dòng)態(tài)加載組件在使用VueRouter進(jìn)行路由跳轉(zhuǎn)的過(guò)程中,有時(shí)我們需要根據(jù)路由參數(shù)動(dòng)態(tài)加載組件。但是,有些情況下,我們可能會(huì)遇到一個(gè)常見(jiàn)的錯(cuò)誤:無(wú)法正確使用VueRouter根據(jù)路由參數(shù)動(dòng)態(tài)加載組件。本文將介紹如何解決這個(gè)報(bào)錯(cuò),并提供代碼示例。首先,我們需要明確一點(diǎn):VueRouter可以通過(guò)

C#中如何使用反射和動(dòng)態(tài)加載程序集引言:在C#中,反射(Reflection)是一種強(qiáng)大的機(jī)制,它允許我們?cè)谶\(yùn)行時(shí)獲取和操作程序的元數(shù)據(jù),包括類型信息、成員信息等。而動(dòng)態(tài)加載程序集則是通過(guò)反射來(lái)實(shí)現(xiàn)的一種常見(jiàn)應(yīng)用,并且在一些特定場(chǎng)景中非常有用。本文將詳細(xì)介紹C#中如何使用反射和動(dòng)態(tài)加載程序集,并提供具體的代碼示例。反射的基本概念反射是C#語(yǔ)言中的一項(xiàng)重要功能

Vue技術(shù)開(kāi)發(fā)中如何處理圖片資源的壓縮和動(dòng)態(tài)加載在現(xiàn)代web開(kāi)發(fā)中,圖片資源是不可避免的。然而,大型的高分辨率圖片可能會(huì)影響網(wǎng)頁(yè)的加載速度,影響用戶體驗(yàn)。因此,壓縮和動(dòng)態(tài)加載圖片資源成為了開(kāi)發(fā)中的重要問(wèn)題。本文將介紹如何在Vue技術(shù)開(kāi)發(fā)中處理圖片資源的壓縮和動(dòng)態(tài)加載,并提供具體的代碼示例。一、圖片壓縮為了提高網(wǎng)頁(yè)的加載速度,我們可以對(duì)圖片資源進(jìn)行壓縮處理。在

Java中使用System類的load()方法動(dòng)態(tài)加載類或資源在Java的開(kāi)發(fā)中,有時(shí)候我們需要在程序運(yùn)行時(shí)動(dòng)態(tài)地加載類或資源,以實(shí)現(xiàn)一些靈活的功能。Java提供了System類的load()方法來(lái)實(shí)現(xiàn)這個(gè)需求。本文將介紹System類的load()方法的使用,并提供相應(yīng)的代碼示例。首先,我們來(lái)了解一下load()方法的定義:publicstaticvo
