1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <button id="btn">import函数</button>
  11. <button id="dynamic">动态引入</button>
  12. </body>
  13. </html>
  14. <!--
  15. import 引用
  16. 需要定义类型 type="module"
  17. -->
  18. <script type="module">
  19. import { createDom } from "./index.js";
  20. createDom()
  21. </script>
  22. <!-- import函数 -->
  23. <script>
  24. btn.addEventListener('click',()=>{
  25. import('./app.js')
  26. .then(fn =>{
  27. fn.createDom()
  28. })
  29. })
  30. // 动态引入
  31. let lock = true;
  32. dynamic.addEventListener('click',()=>{
  33. if(lock){
  34. lock = false
  35. }else{
  36. lock = true;
  37. }
  38. import(path()).then(d =>{
  39. d.createDom()
  40. })
  41. })
  42. function path(){
  43. if(lock){
  44. return './path.js'
  45. }else{
  46. return ''
  47. }
  48. }
  49. </script>

直接引用

  1. export const createDom = ()=>{
  2. const oDiv = document.createElement('div');
  3. oDiv.innerHTML = 'import直接引用';
  4. document.body.appendChild(oDiv);
  5. }

函数引用 - 按需引入

  1. export const createDom = ()=>{
  2. const oDiv = document.createElement('div');
  3. oDiv.innerHTML = 'import函数';
  4. document.body.appendChild(oDiv);
  5. }

动态引入

  1. export const createDom = ()=>{
  2. const oDiv = document.createElement('div');
  3. oDiv.innerHTML = 'import动态引入';
  4. document.body.appendChild(oDiv);
  5. }