1. Reduce HTTP requests

CSS Sprites:

Combine multiple images into a single image and display it through background-position.

Merge stylesheets and scripts:

Combine imported CSS and JS files into one style sheet;

Iii. Using CDN:

Loading static resources (such as images, CSS, JS third-party libraries, etc.) that are not frequently updated and modified is because CDN domain names are generally cached locally and CDN network request speed is very fast.

2. Non-core code loads asynchronously

A, defer:

It is executed after the HTML is parsed. If there are more than one, it is executed in the order that the HTML is loaded

Second, the async:

Execute immediately after loading. If there are more than one, the execution sequence is independent of the loading sequence

The demo:

<script src="defer.js" defer></script>
<script src="async.js" async></script>
Copy the code

3. Use the browser cache

Strong cache

Response Headers

  1. Cache-Control: no-cache / no-store / max-age=8640000
  2. Expires: "Last modification time of resource"

Negotiate the cache

Response Headers

  1. Etag: "Unique identification of resources"
  2. Last-Modified: "Last Modification time of resource"

Request Headers

  1. Etag: "If-None-Match"

  2. Last-Modified: "If-Modified-Since"

4. Pre-resolve DNS

  1. Use to pre-resolve DNS

  2. In advanced browsers, DNS pre-resolution is enabled for all a tabs on the page by default. In many browsers, DNS pre-resolution is disabled for pages opened using HTTPS.
    Force DNS preresolution for tag A to be enabled

Lazy loading

<img src="preview.png" data-src="real.png">

<script>
    const myImg = document.getElementsByTagName('img')[0]
    myImg.src = myImg.getAttribute('data-src')
</script>
Copy the code

6. Use anti-shake and throttling

1. Debounce

const debounce = function(fn, delay = 300) {
    let timer = null
    return function() {
        if(timer) {
            clearTimeout(timer)
        }

        timer = setTimeout(function() {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}
Copy the code

Ii. Throttle

const throttle = function(fn, delay = 60) {
    let timer = null
    return function() {
        if(timer) {
            return 
        }
        
        timer = setTimeout(function() {
            fn.apply(this, arguments)
            timer = null
        }, timer)
    }
}
Copy the code

7. DOM query /DOM operation

Cache DOM queries

const myBox = document.getElementById('myBox')

myBox.addEventListener('click', (event) => {
    console.log(event.target)    
})
Copy the code

Second, for frequent DOM operations, merge together and insert DOM structures

const myList = document.getElementById('myList')

const myFragment = document.createDocumentFragment()

for(let i = 0; i < 10; i++) {
    const li = document.createElement('li')
    li.innerHTML = i
    myFragment.appendChild(li)
}

myList.appendChild(myFragment)
Copy the code