Dynamic imports in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for dynamic imports in JavaScript −

Example

 Live Demo

<!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;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Dynamic imports in JavaScript.</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to dynamically import modules
</h3>
<script>
   document.querySelector(".Btn").addEventListener("click", loadModule);
   let resEle = document.querySelector(".result");
   async function loadModule() {
      let test = await import("./sample.js");
      resEle.innerHTML += test.testImport() + "<br>";
      resEle.innerHTML += test.tellTime();
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Updated on 17-Jul-2020 07:37:11

Advertisements