Web Performance – JS optimization

The position of the script tag

  1. The Script tag can block rendering, delaying the page’s display in the browser.
  2. Placing the

If you can manage script execution, using the Async property (asynchronous loading) provides further performance.

  1. Jq.js and A.js are async at the same time, a.js depends on Jq, a.js is small, so it must be loaded first, at this time, JQ is not initialized, it will report an error)
  2. Managing the execution of interdependent scripts using Async can be a challenge. Third-party script loading libraries, such as Alameda or RequireJS, can provide a convenient interface for managing script dependencies, while also providing the benefits of asynchronous script loading and execution.
  • Import (‘moment’). Then (moment => {XXX})

For details, see the blog’s sister posts: and

Streamlined Resource Programme

  1. JQ compact solutions such as Zepto (if you still use jQ, you can consider using native, the best performance)
  2. Various third-party sources vender also has mini compressed versions
  3. Fetch API
    • Provides a convenient native interface for requesting remote resources through AJAX. You can also effectively polyfill it for browsers that don’t support it.

Js animation

To write JS animations, use requestAnimationFrame instead of timer (which improves rendering and drawing speed), and the Velocity animation library (which can be removed from JQ animations).

Efficient DOM manipulation

For more information, see the blog’s sister article: Web Performance – Optimizing DOM Operations (Rearrange and redraw)

Js operation optimization

JS various loop performance comparison

  • Conclusion: Performance: Plain for loop > forEach > for of > Map > for in
    • ForEach and map cannot be stopped in traversal

Use web workers for computationally intensive or high-latency tasks

Core: Some computation-intensive or high-latency tasks that can be handled with the Web Worker

The JavaScript language uses a single-threaded model, where all tasks can only be done on one thread, one thing at a time.

  • The first task is not finished, the next task has to wait. With the enhancement of computer computing ability, especially the emergence of multi-core CPU, single thread brings great inconvenience and can not give full play to the computing ability of the computer.

The function of Web Worker is to create a multithreaded environment for JavaScript, allowing the main thread to create Worker threads and assign some tasks to the latter to run.

  • While the main thread is running, the Worker thread is running in the background without interfering with each other.
  • Wait until the Worker thread completes the calculation and returns the result to the main thread.

The benefits are:

  • For computationally intensive or high-latency tasks that are burdened by Worker threads, the main thread (typically responsible for UI interactions) will flow smoothly and not be blocked or slowed down.

Once a Worker thread is created, it is always running and is not interrupted by activity on the main thread, such as a user clicking a button or submitting a form.

  • This facilitates communication that responds to the main thread at any time. However, this also causes the Worker to consume resources, so it should not be overused and should be closed once it is used

Use:

var worker = new Worker('oneWork.js'); // The argument to the Worker() constructor is a script file that is the task to be performed by the Worker thread. Since the Worker cannot read local files, the script must come from the network. If the download does not succeed (such as a 404 error), the Worker silently fails.

worker.postMessage('Hello World'); // You can send a message to onework.js
worker.postMessage({method: 'echo'.args: ['Work']}); // You can send a message to onework.js

worker.onmessage = function (event) { / / to monitor oneWork. Js
  console.log('Received message ' + event.data); // Get the return value of onework.js
  doSomething(event.data);
}

function doSomething(data) {
  console.log('Received message ' + data);
  // Execute the task.// This is done
  worker.postMessage('Work done! ');
}

// When Worker completes the task, it closes the Worker (such as placing it in vue's beforeDestory(){})
worker.terminate();
Copy the code

Offline caching with service workers

A JavaScript Worker that runs on a separate thread, separate from all other scripting activity that occurs on the main processing thread

  • HTTPS is required (native development is optional)

Offline caching

Principle: Allows users to intercept network requests and conditionally store items in a special cache through the CacheStorage API.

  • This cache is separate from the browser’s local cache and is used to provide content to users from the CacheStorage cache when they are offline. You can also use this special cache to improve page rendering performance
    • The CacheStorage is used in conjunction with the Fetch event of the Service Worker to intercept and cache network requests. In an outage, an interface intercepts network requests and reads or writes data from the CacheStorage cache

Offline cache resource update problem – similar to browser cache solution

  1. Always fetch the latest index.html (and cache it). If it fails to return (disconnection), use the cached index.html
  2. If a resource is updated, just update the name of the resource (with hash value).
  3. After the resource is updated, you need to handle the invalid resource
    1. Change the cacheVersion variable from v1 to v2 and remove all caches (.delete()) that are not whitelisted to ensure that the site cleans up stale resources as they change

Specific operation can refer to: www.zhangxinxu.com/wordpress/2…


The future may continue to improve, there are questions and errors can leave a message, if useful, thank you for the praise ~

Web worker part, reference www.ruanyifeng.com/blog/2018/0…


Performance optimization set quick entry:

  • How to determine the best caching strategy for front-end resources?
    • Starting point for browser Cache- > cache-control
    • Browser caching mechanism (combined with response headers)
  • The relationship between <link> and <script> and DOM parsing rendering
    • Introduction to browser multi-process architecture
  • Understand Web performance concepts and common analysis tools
    • Using the Web performance analysis tools PageSpeed Insights and Lighthouse Tutorial
  • Web Performance – White screen time details and optimization
    • Web Performance -HTML and CSS optimization
    • Web Performance – Image optimization
    • Web Performance – Font optimization
    • Web Performance – JS optimization
    • Web Performance – Optimizing DOM operations (rearrange and redraw)
    • The basic principle of TCP transmission and optimization
    • Web Performance -CDN architecture introduction and optimization
      • Configure the CDN of the third-party library in the Webpack project and perform CDN fault tolerance
  • Front-end performance monitoring for real users