Home Web Front-end H5 Tutorial An introduction to some details that can be optimized in HTML5

An introduction to some details that can be optimized in HTML5

Oct 29, 2018 pm 04:20 PM
css html html5 javascript

This article brings you some details that can be optimized in HTML5. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introducing some recently organized optimization details. I won’t talk about image compression, this is what optimization must do. Today I will talk about the details of optimization that everyone can cultivate when writing code.

  • Do not abuse float. Don't abuse web fonts.

Float requires a large amount of calculation during rendering, and will be off-standard and collapsed. We can use flex layout instead. The introduction of web fonts requires a lot of effort, so it is best to mention it to the designer and not too much.

  • Avoid redundant style settings in css.

color, font, line-height, etc. can all be inherited, so if their child elements have the same attributes, they must be written repeatedly, especially font-family.

  • A complex method that can cache the return value of a function.

function cached (fn) {
    var cache = Object.create(null);
    return (function cachedFn (str) {
        var hit = cache[str];
        return hit || (cache[str] = fn(str))
    })
};
var fk = function (str) {
  return str.charAt(0).toUpperCase() + str.slice(1)
}
var cacheFk = cached(fk)
// 1 step
cacheFk('ui') 
//2 step
cacheFk('ui')
Copy after login

This is a piece of code I found when I was looking at the vue source code. Its function is to cache the value of a complex function and avoid repeated calculations if the parameters are the same. But the thing to note here is that this caching function is done through closures, so there are some trade-offs.

  • Reduce layout as much as possible.

// 触发两次 layout
var newWidth = p.offsetWidth + 50;
p.style.width = newWidth + 'px';
var newHeight = p.offsetHeight + 50;
p.style.height = newHeight + 'px';

// 只触发一次 layout
var newWidth = p.offsetWidth + 50;
var newHeight = p.offsetHeight + 50;
p.style.width = newWidth + 'px';
p.style.height = newHeight + 'px';
Copy after login

All operations that can trigger layout will be temporarily put into the layout-queue. When it must be updated, the results of all operations in the entire queue will be calculated, so that only Perform a layout to improve performance.

Animation elements are best off-label and do not affect other modules. This is also done so as not to affect other elements.

  • transform instead of position.

To do some CSS displacement effects, it is best to use transform instead of positioning. When I first started, I used position to make animation cards~~~

  • Select the dom element and use the id, but do not define the id for setting the css.

If you use the id selector, do not add other class constraints. Defining too many IDs will reduce reusability and make maintenance more difficult, so it is not recommended to use multiple IDs in CSS.

  • When using length multiple times, use a variable to save it.

var len = dom.length;
for(var i = 0;i < len;i++){};
Copy after login

The advantage of this is that you don’t have to calculate the length of the dom every time you loop.

  • requestAnimationFrame replaces setTimeout

var start = null;
var element = document.getElementById(&#39;SomeElementYouWantToAnimate&#39;);
element.style.position = &#39;absolute&#39;;

function step(timestamp) {
  if (!start) start = timestamp;
  var progress = timestamp - start;
  element.style.left = Math.min(progress / 10, 200) + &#39;px&#39;;
  if (progress < 2000) {
    window.requestAnimationFrame(step);
  }
}

window.requestAnimationFrame(step);
//window.requestAnimationFrame(callback);
返回值是一个 long 整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 window.cancelAnimationFrame() 以取消回调函数。
Copy after login

requestAnimationFrame is a timer that does not need to set the time. It runs every 1/60s. This is based on the browser refresh. Depends on the number of frames. But compatibility is a problem. If you use it, you need to write it well.

  • If possible, try to avoid global searches.

//dom = document.querySelector("#id");
function test() {
    dom = document.querySelector("#id");
}
Copy after login

For example, if you only use dom in the test, do not define it globally, because it will be searched in the internal scope of the test function during execution, which will be faster.

  • Do not use for in unless you don’t know the length of the traversal or the traversal object

    function t1(){        //20ms
        var i = 0;
       for(item in anObj) {
           i++
       }
       if( i === 100000){
           console.log(&#39;for in ok&#39;)
       }
    }
    function t2(){     //4ms
        var len = anObj.length;
        var i = 0;
        for(var i = 0 ;i < len;i++){
            i++
        }
        if( i === 100000){
            console.log(&#39;for ok&#39;)
        }
    }
Copy after login

This is my own test loop of an array of 100,000 elements. The resulting execution time (see code). So it's best not to use it, generally traversing objects will not be used in practice. If there are special circumstances when traversing objects, you should also pay attention! ! ! The things traversed are not themselves. I thought that for in would traverse its prototype chain.

  • Skeleton screen

This is to enhance the user experience, similar to the enhanced version of loading. There are automated generation solutions. You can take a look if you are interested.

  • ios prohibits the page from identifying mobile phone numbers. Android prohibits recognition of email addresses.

<meta name="format-detection" content="telephone=no" />
<meta name="format-detection" content="email=no" />
Copy after login
  • Head css bottom js.

As everyone knows, js will block the parsing of dom and increase the white screen time. So be sure to pay attention.

In fact, there are many details in optimization, so you must cultivate your coding habits, accumulate a little, and slowly accumulate, the quality of the code will definitely be different.

The above is the detailed content of An introduction to some details that can be optimized in HTML5. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles