Tối ưu hóa thao tác với DOM trong JavaScript
Thao tác với DOM là một thao tác chậm. Vì vậy cần phải giảm thiểu việc lấy phần tử, đọc và ghi dữ liệu, đặc biệt là trong vòng lặp.
Hãy xem qua một ví dụ. Giả sử chúng ta có một ô input, trong đó nhập vào một số:
<input>
Hãy kiểm tra khi mất tiêu điểm, số được nhập có nằm trong khoảng đã cho không:
let input = document.querySelector('input');
input.addEventListener('blur', function() {
if (+input.value > 0 && +input.value <= 10) {
console.log('+++');
} else {
console.log('---');
}
});
Vấn đề là chúng ta đọc giá trị từ ô input hai lần, mặc dù số trong đó không thay đổi. Điều này, tất nhiên, không tối ưu. Hãy tối ưu hóa:
let input = document.querySelector('input');
input.addEventListener('blur', function() {
let num = +input.value;
if (num > 0 && num <= 10) {
console.log('+++');
} else {
console.log('---');
}
});
Đoạn mã sau kiểm tra giá trị được nhập. Hãy thực hiện tối ưu hóa:
<input>
let input = document.querySelector('input');
input.addEventListener('blur', function() {
if (input.value === '1' || input.value === '2') {
console.log('+++');
} else {
console.log('---');
}
});
Đoạn mã sau tìm tổng các số nguyên từ một đến số được nhập vào ô input. Hãy thực hiện tối ưu hóa:
<input>
let input = document.querySelector('input');
input.addEventListener('blur', function() {
let sum = 0;
for (let i = 1; i <= +input.value; i++) {
sum += i;
}
console.log(sum);
});
Đoạn mã sau tìm tổng các ước số của số được nhập vào ô input. Hãy thực hiện tối ưu hóa:
<input>
<div></div>
let input = document.querySelector('input');
input.addEventListener('blur', function() {
let sum = 0;
for (let i = 1; i <= +input.value; i++) {
if (input.value % i === 0) {
sum += i;
let div = document.querySelector('div');
div.textContent = sum;
}
}
});
Đoạn mã sau tính bình phương các số từ các đoạn văn. Hãy thực hiện tối ưu hóa:
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
let elems = document.querySelectorAll('p');
for (let elem of elems) {
elem.textContent = elem.textContent * elem.textContent;
}
Đoạn mã sau kiểm tra xem chuỗi nhập vào ô input có độ dài nằm trong khoảng đã cho không. Hãy thực hiện tối ưu hóa:
<input data-min="5" data-max="10">
let inp = document.querySelector('input');
inp.addEventListener('blur', function() {
if (inp.dataset.min > inp.value.length || inp.dataset.max < inp.value.length) {
console.log('+++');
} else {
console.log('---');
}
});