篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Javascript DOM Manipulation可以提高性能相关的知识,希望对你有一定的参考价值。
//Use selector instead nested elements
// BAD
let menu = document.querySelector('header > nav > ul.menu');
// GOOD
let menu = document.querySelector('.menu');
//Avoid DOM manipulations inside loops
// BAD
for (let i = 0; i < 10; i++) {
document.querySelector('.numbers').innerText += i;
}
// GOOD
let numbers = '';
for (let i = 0; i < 10; i++) {
numbers += i;
}
document.querySelector('.numbers').innerText = numbers;
//Don't use DOM values inside loops
// BAD
let nodes = document.querySelector('.menu-items');
for (let i = 0; i < node.length; i++) { ... }
// GOOD
let nodes = document.querySelector('.menu-items');
const size = nodes.length;
for (let i = 0; i < size; i++) { ... }
//Appending DOM is the most expensive operation, choose the right approach
// BAD
let container = document.querySelector('.container');
for (let i = 0; i < 1000; i++) {
let a = document.createElement('a');
a.text = `Row N° ${i}`;
container.appendChild(a);
}
// GOOD
let container = document.querySelector('.container');
let html = '';
for (let i = 0; i < 1000; i++) {
html = html.concat(`<a>Row N° ${i}</a>`);
}
container.innerHTML = html;
// BETTER
let a = document.createElement('a');
let container = document.querySelector('.container');
for (let i = 0; i < 1000; i++) {
let cloneA = a.cloneNode(true);
cloneA.text = `Row N° ${i}`;
container.appendChild(cloneA);
}
// BETTER^2
let a = document.createElement('a');
let container = document.querySelector('.container');
let documentFragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
let cloneA = a.cloneNode(true);
cloneA.text = `Row N° ${i}`;
documentFragment.appendChild(cloneA);
}
container.appendChild(documentFragment);
//Use innerHTML only for first rendering and then use DOM methods
// BAD
let container = document.querySelector('.container');
container.innerHTML = '<input type="text" name="example" value="Hi DEVS!">';
container.innerHTML = '<input type="text" name="example" value="Bye DEVS!">';
// GOOD
let container = document.querySelector('.container');
container.innerHTML = '<input type="text" name="example" value="Hi DEVS!">';
container.value = 'Bye DEVS!';
以上是关于javascript Javascript DOM Manipulation可以提高性能的主要内容,如果未能解决你的问题,请参考以下文章