JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Dynamic Imports in JavaScript

Keerti Kotaru
JavaScript in Plain English
6 min readMay 6, 2020

--

Figure-1: Browser Compatibility- link to the documentation

Using import() in to-do code sample

Figure-2: To-do sample screens
import getData from './data-module.js';
import { getTodosMarkup } from './todo-list-module.js';
let list = getData();
document.getElementById("todos").innerHTML = getTodosMarkup(list.todos);
const handler = () => {
import ('./create-todo.js').then((module) => {
// access any exported function in the module.
// following createTodo() generates DOM string for Create Todo
// set the DOM string on an element.
document.getElementById("createTodo").innerHTML = module.createTodo();
});
}
// click event handler added on the hyperlink, “Create Todos”.
document
.getElementById("btnCreateTodo")
.addEventListener("click", handler);
Figure-3: Script loads only after navigating to Create to-do screen

Code Sample

const asyncHandler = async() => { if (isList) {
isList = false;
let module = await import ('./create-todo.js')
document.getElementById("createTodo").innerHTML =
module.createTodo();
};
/* The module name is unavailable pre-runtime as it's created on the fly with using CREATE_TODO_URL */import (`./${CREATE_TODO_URL}.js`)

Notes

<script type="module" src="./JS/index.js"></script>

How are new features added to JavaScript?

A note from the Plain English team

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

No responses yet

Write a response