- read

9 Super Useful Javascript Tips

Xiuer Old 72

9 Super Useful Javascript Tips

Xiuer Old
JavaScript in Plain English
7 min read4 days ago

--

Preface

During the actual development work, I have accumulated some common and super easy-to-use Javascript techniques and code snippets, including compiled JS usage techniques from other masters. Today I have selected 9 of them for your reference.

1. Dynamically load JS files

In some special scenarios, especially in the development of some libraries and frameworks, we sometimes dynamically load JS files and execute them. The following is a simple 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 uses very little code to implement a dynamic template rendering engine. It not only supports the replacement of ordinary dynamic variables, but also supports dynamic JS syntax logic including for loops, if judgments, etc. The specific implementation logic is in another article of the author. “Interviewer asked: Can you handwrite a template engine? “ It gives a very detailed explanation, and interested friends can read it by themselves.

// This is a dynamic template containing js code
var template =
'My favorite sports:' +
'<%if(this.showSports) {%>' +
'<% for(var index in this.sports) { %>' +
'<a><%this.sports[index]%></a>' +
'<%}%>' +
'<%} else {%>' +
'<p>none</p>' +
'<%}%>';
// This is the function string we want to concatenate
const code = `with(obj) {
var r=[];
r.push("My favorite…