創(chuàng)建script元素並添加到DOM可動態(tài)加載JavaScript文件;2. 使用Promise封裝可實現(xiàn)更簡潔的異步控制;3. 需注意執(zhí)行順序、CORS、安全風(fēng)險及重複加載問題;4. 可通過Set記錄已加載腳本防止重複加載。該方法適用於懶加載、第三方組件或條件性功能,且必須確保腳本來源可信,最終通過onload或onerror回調(diào)處理結(jié)果,整個過程由瀏覽器自動完成腳本的下載與執(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.
以上是您如何動態(tài)加載JavaScript文件?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

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

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

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

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

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

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python實作無頭瀏覽器擷取應(yīng)用程式的頁面動態(tài)載入與非同步請求處理功能解析在網(wǎng)路爬蟲中,有時需要擷取使用了動態(tài)載入或非同步請求的頁面內(nèi)容。傳統(tǒng)的爬蟲工具對於這類頁面的處理有一定的局限性,無法精確地取得頁面上透過JavaScript產(chǎn)生的內(nèi)容。而使用無頭瀏覽器則可以解決這個問題。本文將介紹如何使用Python實作無頭瀏覽器來擷取使用動態(tài)載入與非同步請求的頁面內(nèi)容

Vue中處理組件的動態(tài)載入和切換Vue是一個流行的JavaScript框架,它提供了各種靈活的功能來處理組件的動態(tài)載入和切換。在本文中,我們將討論一些Vue中處理元件動態(tài)載入和切換的方法,並提供具體的程式碼範(fàn)例。動態(tài)載入元件是指根據(jù)需要在執(zhí)行時期動態(tài)載入元件。這樣可以提高應(yīng)用程式的效能和載入速度,因為只有當(dāng)需要時才會載入相關(guān)的元件。 Vue提供了async和awa

如何使用Vue和Element-UI建立動態(tài)載入資料的表格在現(xiàn)代的Web開發(fā)中,資料表格是常見的介面元件之一。 Vue.js是當(dāng)下非常受歡迎的前端框架,而Element-UI是基於Vue.js開發(fā)的一套元件庫,提供了豐富的UI元件供我們使用。本文將介紹如何使用Vue和Element-UI來建立一個可以動態(tài)載入資料的表格,並且給出對應(yīng)的程式碼範(fàn)例。首先,我們需要安裝

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

解決Vue報錯:無法正確使用VueRouter根據(jù)路由參數(shù)動態(tài)載入元件在使用VueRouter進(jìn)行路由跳轉(zhuǎn)的過程中,有時我們需要根據(jù)路由參數(shù)動態(tài)載入元件。但是,在某些情況下,我們可能會遇到一個常見的錯誤:無法正確使用VueRouter根據(jù)路由參數(shù)動態(tài)載入元件。本文將介紹如何解決這個報錯,並提供程式碼範(fàn)例。首先,我們需要明確一點:VueRouter可以透過

C#中如何使用反射和動態(tài)載入組件引言:在C#中,反射(Reflection)是一種強(qiáng)大的機(jī)制,它允許我們在運(yùn)行時獲取和操作程式的元數(shù)據(jù),包括類型資訊、成員資訊等。而動態(tài)載入程式集則是透過反射來實現(xiàn)的常見應(yīng)用,並且在一些特定場景中非常有用。本文將詳細(xì)介紹C#中如何使用反射和動態(tài)載入組件,並提供具體的程式碼範(fàn)例。反射的基本概念反射是C#語言中的重要功能

Vue技術(shù)開發(fā)中如何處理圖片資源的壓縮和動態(tài)載入在現(xiàn)代web開發(fā)中,圖片資源是不可避免的。然而,大型的高解析度圖片可能會影響網(wǎng)頁的載入速度,影響使用者體驗。因此,壓縮和動態(tài)載入圖片資源成為了開發(fā)中的重要議題。本文將介紹如何在Vue技術(shù)開發(fā)中處理圖片資源的壓縮和動態(tài)加載,並提供具體的程式碼範(fàn)例。一、圖片壓縮為了提高網(wǎng)頁的載入速度,我們可以對圖片資源進(jìn)行壓縮處理。在

Java中使用System類別的load()方法動態(tài)載入類別或資源在Java的開發(fā)中,有時候我們需要在程式執(zhí)行時動態(tài)地載入類別或資源,以實作一些靈活的功能。 Java提供了System類別的load()方法來實作這個需求。本文將介紹System類別的load()方法的使用,並提供對應(yīng)的程式碼範(fàn)例。首先,讓我們來了解一下load()方法的定義:publicstaticvo
