Awaiting on dynamic imports in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

Note − You will need a localhost server to run this example −

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>Awaiting on 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>

sample.js

function testImport() {
   return "Module testImport has been imported" + "<br>";
   }
   function tellTime() {
      return new Date();
   }
export { testImport, tellTime };

Output

On clicking the ‘CLICK HERE’ button −

raja
Updated on 22-Jul-2020 07:42:30

Advertisements