Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tải JavaScript modules động (Dynamic Import)

Dưới đây là mã về tải JavaScript modules động.

Lưu ý - Bạn cần chạy localhost server để chạy ví dụ này.

Ví dụ

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .result {       font-size: 18px;       font-weight: 500;     } </style> </head> <body> <h1> Tải JavaScript modules động</h1> <button class="Btn">IMPORT</button> <div class="result"></div> <h3>Nhấn nút trên để import module</h3> <script src="script.js" type="module"></script> <script src="sample.js" type="module"></script> </body> </html>

script.js

import test from './sample.js'; document.querySelector('.Btn').addEventListener('click',()=>{ test(); })

sample.js

let resultEle = document.querySelector(".result"); export default function testImport(){ resultEle.innerHTML = 'Module testImport has been imported'; }

Kết quả

Tải JavaScript modules động (Dynamic Import)

Khi nhấn nút 'IMPORT':

Tải JavaScript modules động (Dynamic Import)