Performance optimization trivia

wang xiao bo 's photo
wang xiao bo
·Feb 18, 2022·

6 min read

Performance optimization trivia

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Image optimization
  • DNS pre-resolution
  • throttling
  • anti-shake
  • Preloading
  • lazy execution
  • lazy loading
  • CDN
  • summary

Note: This knowledge point belongs to the field of performance optimization.

In general, a lot of content in the field of performance optimization is fragmented, and in this chapter we will learn about these fragmented content in the future.

Image optimization

Calculate image size

For a 100 100 pixel image, there are 10,000 pixels on the image. If the value of each pixel is stored in RGBA, then each pixel has 4 channels, and each channel has 1 byte. (8 bits = 1 byte), so the image size is about 39KB (10000 1 * 4 / 1024).

But in practical projects, a picture may not need to use so many colors to display, we can reduce the size of the picture by reducing the color palette of each pixel.

Knowing how to calculate the image size, you must have 2 ideas on how to optimize the image:

  • reduce pixels
  • Reduce the color that each pixel can display

Image loading optimization

  1. No pictures. Many times, a lot of decorative images are used. In fact, this kind of decorative images can be replaced by CSS.

  2. For the mobile terminal, the screen width is so small, there is no need to load the original image to waste bandwidth. Generally, pictures are loaded by CDN, and the width of the screen can be calculated, and then the corresponding cropped pictures can be requested.

  3. Thumbnails use base64 format

  4. Combine multiple icon files into one image (sprite image)

  5. Choose the correct image format:

  6. For browsers that can display WebP format, try to use WebP format. Because the WebP format has a better image data compression algorithm, it can bring a smaller image size, and it has image quality that is indistinguishable to the naked eye. The disadvantage is that the compatibility is not good.

  7. PNG is used for small images. In fact, for most images such as icons, SVG can be used instead.

  8. Photos use JPEG

DNS pre-resolution

DNS resolution also takes time, and the IP corresponding to the domain name can be obtained in advance through pre-resolution.

  link rel="dns-prefetch" href="baidu.com">

throttling

Consider a scenario where a network request will be initiated in the scroll event, but we don't want the user to initiate the request all the time during the scrolling process, but once in a while, in this case we can use throttling.

Understand the purpose of throttling, let's implement this function

// func is the function passed in by the user that needs anti-shake
// wait is the wait time
const throttle = (func, wait = 50) => {
// The last time the function was executed
let lastTime = 0
return function(...args) {
// current time
let now = +new Date()
// Compare the current time with the last time the function was executed
// If the difference is greater than the set waiting time, execute the function
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}
setInterval(
throttle(() => {
console.log(1)
}, 500),
1
)

anti-shake

Consider a scenario where a button click will trigger a network request, but we don't want to initiate a network request every time the click is clicked, but only when the user clicks the button for a period of time and does not click again. For this case We can use anti-shake.

Understand the purpose of anti-shake, let's implement this function

// func is the function passed in by the user that needs anti-shake
// wait is the wait time
const debounce = (func, wait = 50) => {
// cache a timer id
let timer = 0
// The function returned here is the anti-shake function that the user actually calls each time
// If the timer has been set, clear the last timer
// Start a new timer and delay execution of the method passed in by the user
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}

Preloading

In development, such a situation may be encountered. Some resources do not need to be used immediately, but you want to get them as soon as possible, and you can use preloading at this time.

Preloading is actually a declarative fetch , which forces the browser to request resources and does not block the onload event. You can use the following code to enable preloading

<link rel="preload" href="http://example.com">

Preloading can reduce the loading time of the first screen to a certain extent, because some important files that do not affect the first screen but are loaded can be delayed. The only disadvantage is that the compatibility is not good.

<link rel="prerender" href="http://example.com">

Although pre-rendering can improve the loading speed of the page, it is necessary to ensure that the page is likely to be opened by the user later, otherwise it is a waste of resources to render.

lazy execution

Lazy execution is when some logic is delayed until it is used. This technology can be used for first screen optimization. For some time-consuming logic that does not need to be used on the first screen, lazy execution can be used. Lazy execution needs to be woken up, which can generally be woken up by calling a timer or an event.

lazy loading

Lazy loading is to delay loading of uncritical resources.

The principle of lazy loading is to only load what needs to be loaded in the custom area (usually the visible area, but it can also be about to enter the visible area). For images, first set the src attribute of the image tag as a placeholder image, put the real image resource into a custom attribute, and when entering the custom area, replace the custom attribute with the src attribute, so that The picture will go to download the resource, realizing the lazy loading of the picture.

Lazy loading can be used not only for images, but also for other resources. For example, the video starts to play after entering the visible area, and so on.

CDN

The principle of CDN is to distribute cached data in computer rooms as much as possible, so that even if our root server is far abroad, users in China can quickly load resources through domestic computer rooms.

Therefore, we can use CDN to load static resources as much as possible. Since the browser has an upper limit of concurrent requests for a single domain name, we can consider using multiple CDN domain names. And for CDN to load static resources, it should be noted that the CDN domain name should be different from the main site, otherwise each request will bring the main site's cookie, consuming traffic in vain.

summary

These fragmented performance optimization points seem to be very short, but they can improve performance simply and efficiently when performance problems occur, such as throttling and anti-shake. If you have not used these techniques in your project, you can try to use them in the project and experience the effect.

 
Share this