How to optimize JavaScript performance? Do you know 12 ways to optimize?

Insert image description here


When it comes to JavaScript performance optimization, there are several key aspects to consider. Here are some common JavaScript performance optimization tips and practices:

Reduce DOM operations:

Frequent DOM operations will cause redrawing and relayout, affecting performance. It is recommended to combine multiple DOM operations into one operation, or use DocumentFragment to insert DOM elements in batches.

// 不推荐写法(频繁操作DOM)
const container = document.getElementById('container');
for (let i = 0; i < 1000; i++) {
    
    
  const element = document.createElement('div');
  element.textContent = 'Item ' + i;
  container.appendChild(element);
}

// 推荐写法(合并DOM操作)
const container = document.getElementById('container');
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
    
    
  const element = document.createElement('div');
  element.textContent = 'Item ' + i;
  fragment.appendChild(element);
}
container.appendChild(fragment);

Avoid unnecessary redraws and reflows:

Redrawing and reflow consume a lot of computing resources. Try to avoid modifying style properties or getting layout information in a loop. If you need to modify multiple styles, you can use CSS class switching.

// 不推荐写法(频繁触发重绘和回流)
const element = document.getElementById('myElement');
for (let i = 0; i < 1000; i++) {
    
    
  element.style.left = i + 'px';
  element.style.top = i + 'px';
}

// 推荐写法(使用CSS class)
const element = document.getElementById('myElement');
element.classList.add('move');

// CSS样式:
// .move {
    
    
//   left: 1000px;
//   top: 1000px;
// }

Use event delegation:

Binding event listeners to parent elements and using the event bubbling mechanism to handle events on child elements can reduce the number of event processing functions and improve performance.

// 不推荐写法(为每个子元素添加事件监听器)
const items = document.querySelectorAll('.item');
items.forEach((item) => {
    
    
  item.addEventListener('click', () => {
    
    
    // 处理点击事件
  });
});

// 推荐写法(使用事件委托)
const container = document.getElementById('container');
container.addEventListener('click', (event) => {
    
    
  if (event.target.classList.contains('item')) {
    
    
    // 处理点击事件
  }
});

Use throttling and anti-shake:

When processing some high-frequency triggered events (such as resize, scroll), using throttling and debouncing can limit the execution frequency of event processing functions and improve performance.

// 节流
function throttle(func, delay) {
    
    
  let timerId;
  return function (...args) {
    
    
    if (!timerId) {
    
    
      timerId = setTimeout(() => {
    
    
        func(...args);
        timerId = null;
      }, delay);
    }
  };
}


// 防抖
function debounce(func, delay) {
    
    
  let timerId;
  return function (...args) {
    
    
    clearTimeout(timerId);
    timerId = setTimeout(() => {
    
    
      func(...args);
    }, delay);
  };
}

// 使用节流处理scroll事件
window.addEventListener('scroll', throttle(handleScroll, 200));

// 使用防抖处理输入事件
input.addEventListener('input', debounce(handleInput, 300));

Reduce network requests:

Reducing the number of HTTP requests can significantly improve page loading speed. You can combine multiple scripts or style sheets into a single file, use CSS Sprites technology to reduce image requests, use CDN acceleration, etc.
These are some common JavaScript performance optimization tips and practices. Depending on the actual situation, you can choose an optimization strategy suitable for your project to improve the performance of JavaScript code. Remember, before writing optimized code, perform performance testing and analysis to determine which parts need optimization.

Please note that optimizing performance is not limited to the JavaScript code itself, but also needs to consider other factors, such as network latency, server response time, caching strategy, etc.
When it comes to JavaScript performance optimization, there are several key aspects to consider. Here are some common JavaScript performance optimization tips and practices:

Using Web Workers:

For tasks that involve a lot of calculations or time-consuming operations, you can put them into a Web Worker and run them in a background thread to avoid blocking the main thread and improve page response performance.

// 主线程代码
const worker = new Worker('worker.js');
worker.postMessage('Hello from main thread!');
worker.onmessage = function (event) {
    
    
  const result = event.data;
  // 处理Worker返回的结果
};

// worker.js代码
self.onmessage = function (event) {
    
    
  const message = event.data;
  // 执行计算或耗时操作
  const result = doSomeWork(message);
  self.postMessage(result);
};

Lazy loading resources:

Delay the loading of non-critical resources (such as pictures, scripts, etc.) and load them when the user needs them, reducing the initial loading time of the page and improving the user experience.

<!-- 图片懒加载 -->
<img data-src="image.jpg" class="lazyload" alt="Lazy-loaded Image">

<script>
  // 使用Intersection Observer检测元素是否进入视口
  const lazyloadImages = document.querySelectorAll('.lazyload');
  const observer = new IntersectionObserver(function (entries, observer) {
    
    
    entries.forEach(function (entry) {
    
    
      if (entry.isIntersecting) {
    
    
        const img = entry.target;
        img.src = img.dataset.src;
        observer.unobserve(img);
      }
    });
  });
  lazyloadImages.forEach(function (img) {
    
    
    observer.observe(img);
  });
</script>

Use caching:

Make reasonable use of the browser caching mechanism to reduce unnecessary requests. Set the correct Cache-Control and Expires header information to let the browser cache static resources.

//设置缓存过期时间为1年(根据实际情况调整)
<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault "access plus 1 year"
</IfModule>

Code optimization and compression:

Optimize and compress JavaScript code, remove unnecessary spaces, comments and code blocks, reduce file size, and speed up loading. Optimize
code through reasonable algorithms and data processing methods: Suppose we need to calculate the sum of all elements in an array, we can

以使用reduce方法来避免显式的循环。
javascript
const numbers = [1, 2, 3, 4, 5];

// 使用 reduce 方法计算数组元素的总和
const sum = numbers.reduce((acc, curr) => acc + curr, 0);

console.log(sum); // 输出15

Compress and merge JavaScript files:

Use compression tools (such as UglifyJS) to compress JavaScript files to reduce file size. Additionally, merging multiple JavaScript files into a single file can reduce the number of HTTP requests.

Using Web Workers:

Using Web Workers, you can transfer large amounts of calculations or time-consuming operations to background threads to avoid blocking the main thread. Here is a simple Web Worker example:

// 在主线程中创建Web Worker
const worker = new Worker('worker.js');

// 向Web Worker发送消息
worker.postMessage({
    
     data: 'some data' });

// 接收来自Web Worker的消息
worker.onmessage = function(event) {
    
    
  console.log(event.data);
};

Complex calculations or time-consuming operations can be performed in the Web Worker's code file worker.js and the results are sent back to the main thread through the postMessage method.

Use event caching:

For frequently triggered events, event caching can be used to reduce the number of calls to the event handler function. Here's an example:

// 定义事件缓存标志位
let isProcessing = false;

// 监听滚动事件
window.addEventListener('scroll', function() {
    
    
  // 如果正在处理中,则跳过本次事件
  if (isProcessing) return;

  // 设置处理中标志位
  isProcessing = true;

  // 执行滚动相关操作

  // 在合适的时机重置处理中标志位
  setTimeout(function() {
    
    
    isProcessing = false;
  }, 100);
});

By setting the flag bit before handling the event and resetting the flag bit at the appropriate time, you can prevent the event handling function from being called frequently.

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/131419533