9 Incredibly Useful JavaScript Tips

Choco
6 min readDec 28, 2023

🚀 1. Dynamically Load JS Files

In certain unique scenarios, particularly during the development of libraries and frameworks, there arises a need to dynamically load JS files and execute them. Below is a straightforward encapsulation using Promise.

function loadJS(files, done) {
// Get the head tag
const head = document.getElementsByTagName('head')[0];
Promise.all(files.map(file => {
return new Promise(resolve => {
//Create a script tag and add it to the head
const s = document.createElement('script');
s.type = "text/javascript";
s.async = true;
s.src = file;
//Listen to the load event and resolve if the loading is completed
s.addEventListener('load', (e) => resolve(), false);
head.appendChild(s);
});
})).then(done); // Everything is completed, execute the user's callback event
}
loadJS(["test1.js", "test2.js"], () => {
//User callback logic
});

There are two core points in the above code. One is to use Promise to handle asynchronous logic, and to use script tags to load and execute js.

🛠️ 2. Implement Template Engine

The following example employs minimal code to create a dynamic template rendering engine. It not only facilitates the substitution of regular…

--

--

Choco

Senior Frontend Engineer | React | Angular | Node | Typescript