<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">import函数</button>
<button id="dynamic">动态引入</button>
</body>
</html>
<!--
import 引用
需要定义类型 type="module"
-->
<script type="module">
import { createDom } from "./index.js";
createDom()
</script>
<!-- import函数 -->
<script>
btn.addEventListener('click',()=>{
import('./app.js')
.then(fn =>{
fn.createDom()
})
})
// 动态引入
let lock = true;
dynamic.addEventListener('click',()=>{
if(lock){
lock = false
}else{
lock = true;
}
import(path()).then(d =>{
d.createDom()
})
})
function path(){
if(lock){
return './path.js'
}else{
return ''
}
}
</script>
直接引用
export const createDom = ()=>{
const oDiv = document.createElement('div');
oDiv.innerHTML = 'import直接引用';
document.body.appendChild(oDiv);
}
函数引用 - 按需引入
export const createDom = ()=>{
const oDiv = document.createElement('div');
oDiv.innerHTML = 'import函数';
document.body.appendChild(oDiv);
}
动态引入
export const createDom = ()=>{
const oDiv = document.createElement('div');
oDiv.innerHTML = 'import动态引入';
document.body.appendChild(oDiv);
}