Front-end fragment performance optimization

Our browser implements more and more features, and the network is gradually shifting to mobile devices, making our front-end code more compact. How to optimize it becomes more and more important. Where the front end is powerful is that there can be many simple strategies and code habits that allow us to guarantee the most ideal front-end performance. The theme of our series is to show you 9 kinds of code tips. It only takes a minute to optimize your existing code.

Front-end performance optimization: DocumentFragments or innerHTML replace complex element injection

Use DocumentFragments or innerHTML instead of complex element injection

DOM operations are taxable on the browser. Although the performance improvement is in the browser, the DOM is very slow, if you don't notice, you may notice that the browser is running very slowly. This is why it is so important to reduce the creation of centralized DOM nodes and rapid injection.

Now suppose we have a <ul> element on our page, call AJAX to get the JSON list, and then use JavaScript to update the element content. Usually, programmers would write:

var list = document.querySelector('ul');
ajaxResult.items.forEach(function(item) {
    // Create <li> element
    var li = document.createElement ('li');
    li.innerHTML = item.text;

    // <li> General operation of elements, such as adding class, changing attribute, adding event monitoring, etc.

    // Quickly inject the <li> element into the parent <ul>
    list.apppendChild(li);
});

The above code is actually a wrong way of writing, it is very slow to transplant the <ul> element with DOM operations on each list. If you really want to use document.createElement and treat the object as a node, then you should use DocumentFragement for performance issues.

DocumentFragement is a "virtual storage" of a set of child nodes, and it has no parent label. In our example, imagine DocumentFragement as an invisible <ul> element. Outside the DOM, you keep your child nodes until they are injected into the DOM. Then, the original code can be optimized with DocumentFragment:

var frag = document.createDocumentFragment();

ajaxResult.items.forEach(function(item) {
    // Create <li> element
    var li = document.createElement ('li');
    li.innerHTML = item.text;

    // <li> Element general operations
    // For example, add class, change attribute, add event listener, add child node, etc.

    // Add the <li> element to the fragment
    frag.appendChild(li);
});

Guess you like

Origin www.cnblogs.com/fs0196/p/12691393.html