Hi, I’m CUGGZ and today I’m going to share some HTML tips
1. Input label: Input validation
We usually use JavaScript to validate forms, such as:
function validateForm() {
const inputText = document.forms["form-name"] ["input-name"].value;
if(! inputText) { }else{}}Copy the code
React, Vue and other frameworks are used to implement many projects. Form verification may be a little easier
Here’s a look at the native validation provided by HTML:
Verify the content | Directions for use | The sample |
---|---|---|
mandatory | Force the input | <input required="true"> |
regular | Verify according to regular expression rules | <input pattern="^1\d{10}$"> |
type | Force a content type | <input type="number"> <input type="email"> |
The size of the | Limit the input number size | <input type="number" min="0">``<input type="number" max="5"> |
The input space | Specifies the interval between input numbers | <input type="number" step="1" > |
2. Meta Tags: Automatically refresh/skip
If you want to achieve a PPT autoplay effect, you might want to use JavaScript timer to control the page jump. However, there is a much cleaner way to do this, such as using meta tags:
<meta http-equiv="Refresh" content="5; URL=page2.html">
Copy the code
The above code will automatically jump to page2.html page in the same domain after 5s. To implement the PPT automatic playback function, you only need to set the address of the next page in the meta tag of each page.
Another scenario, such as a large screen monitor that needs to refresh the page every minute, can also be done with meta tags by removing the following URL:
<meta http-equiv="Refresh" content="60">
Copy the code
As you can see, it’s quick and convenient, so why is it so rare?
JavaScript timers are recommended for the refresh interval or manual cancellation of the refresh interval because the refresh and jump operations cannot be cancelled. However, if you only want to periodically refresh or jump to the page (for example, some pages lack access permission and jump back to the home page after x seconds), it is recommended to practice the use of meta tags.
3. Title tag: message alert
Message reminder function is difficult to implement, before the release of HTML5 standard, browsers do not have open icon flashing, pop-up system messages and other interfaces, can only rely on some Hack means, For example, modify the title tag to achieve a similar effect (the Web Notifications API can be used in HTML5 to pop up system messages).
The following code simulates the flashing effect of a message alert by periodically modifying the content of the title tag:
'let msgNum = 1 // Number of messages
let cnt = 0 / / counter
const inerval = setInterval(() = > {
cnt = (cnt + 1) % 2
if(msgNum===0) {
// Change the title using DOM
document.title += 'Chat page'
clearInterval(interval)
return
}
const prefix = cnt % 2 ? 'New news (${msgNum}) ` : ' '
document.title = `${prefix}Chat page '
}, 1000)
Copy the code
The result is as shown in the picture below. You can see the prompt text flashing on the label name.By simulating message flicker, users can know the message returned by the server when browsing other pages.
Regularly modify the content of the title tag, in addition to the flicker effect, can also make other animation effects, such as text scrolling, but need to pay attention to the browser will be on the title tag text to remove the space operation.
The purpose of dynamically changing the title tag is not only to alert message, but also to display some key information (such as download progress, current operation steps) on the tag, thus improving the user experience.
4. Script tags: Adjust the loading order to improve rendering speed
Due to the underlying operating mechanism of the browser, if the rendering engine encountered a script tag reference file when parsing HTML, it would suspend the parsing process and notify the network thread to load the file. After the file is loaded, it would switch to the JavaScript engine to execute the corresponding code. When the code is finished, switch to the rendering engine to continue rendering the page.
As you can see in this process, the page rendering process contains request files and execution file time, but the first rendering of the page may not depend on these files, the request and execution file action will prolong the user’s view of the page, thereby reducing the user experience.
To reduce these time losses, you can use three attributes of the Script tag.
- Async property: requests a file immediately, but does not block the rendering engine, instead blocks the rendering engine and executes the file content immediately after the file is loaded.
- The defer attribute: request the file immediately, but do not block the rendering engine until the HTML has been parsed before executing the file content.
- HTML5 standard type attribute: the corresponding value is “module”. Have the browser parse the file as a module according to ECMA Script 6, blocking as defer by default, or with async executing immediately after the request is complete.
The specific effect can be seen below:Where the green line represents parsing HTML, the blue line represents the request file, and the red line represents the execution file.
As you can see from the figure, all three attributes can reduce the blocking time caused by the request file. Only the defer attribute and type=”module” can ensure the rendering engine to execute first, thus reducing the time consumed by the file content. Allow users to see pages faster, even if the page content may not be fully displayed.
Note that when the rendering engine parses the HTML and encounters a script tag import file, it immediately does a rendering. This is why build tools place compiled script tags that reference JavaScript code at the bottom of the body tag, because when the rendering engine executes at the bottom of the body, it will render the parsed content before requesting the corresponding JavaScript file. If it is an inline script (that is, a form of JavaScript code written directly in HTML without referring to an external script file via the SRC attribute), the rendering engine will not render.
5. Link tags: Speed up rendering through pre-processing
In the performance optimization of large single-page applications, lazy loading on demand may be used to load corresponding modules. However, if the rel attribute value of link tag can be properly used for preloading, rendering speed can be further improved.
- Dns-prefetch: When the REL value of the link label is dns-prefetch, the browser will perform DNS resolution for a domain name and cache it. In this way, when the browser requests resources with the same domain name, it saves the process of querying IP addresses from the domain name, thus reducing the time consumption. The following figure shows the DNS pre-resolution Settings on Taobao.
- Preconnect: Allows the browser to perform some actions before an HTTP request is formally sent to the server. This includes DNS resolution, TLS negotiation, and TCP handshake, saving the user time by eliminating round-trip latency.
- ** Prefetch /preload: ** Both values allow the browser to pre-load and cache a resource, but prefetch may be ignored when the browser is busy, whereas preload must be pre-loaded.
- The browser not only loads resources, but also parses the execution page for pre-rendering.
These attribute values exactly reflect the process of the browser obtaining the resource file. The following is the flow chart:
6. Link labels: Reduce duplication
Sometimes, for user convenience or historical reasons, there are multiple urls for the same page, or there are some redirected pages, such as:
- baidu.com/a.html
- Baidu.com/detail?id= “…”
So in these pages you can set it like this:
<link href="https://baidu.com/a.html" rel="canonical">
Copy the code
This allows search engines to avoid spending time crawling duplicate pages. Note, however, that it also has a restriction, that is to point to the site is not allowed to cross domain.
Of course, there are other ways to combine urls, such as using a site map or adding rel=”canonical” to the HTTP request response header.
7. Pre tags: Pre-formatted text
The Pre element defines pre-formatted text. Text enclosed within a Pre element is usually reserved for Spaces and newlines. Text wrapped with the Pre tag is rendered in a monospaced font. One common use of the Pre tag is to display source code.
Insert the following contents into the Pre label:
<pre> < html> < head> < script type=" text/javascript" src=" loadxmldoc.js" > < /script> < /head> < body> < /body> < /html> </pre>Copy the code
The final display is as follows:
<html>
<head>
<script type="text/javascript" src="loadxmldoc.js">
</script>
</head>
<body>
</body>
</html>
Copy the code
8. Figure tags: Label pictures
The
<figure>
<img src="FM = https://t7.baidu.com/it/u=2604797219, 1573897854 & 193 & f = GIF" alt="Swat Kats" style="width:500px">
<figcaption>landscape</figcaption>
</figure>
Copy the code
9. Picture tag: Responsive image
The picture tag can display different images depending on the size of the screen. If no picture is matched or the browser does not support the picture attribute, use the img element:
<picture>
<source media="(min-width: 968px)" srcset="large_img.jpg">
<source media="(min-width: 360px)" srcset="small_img.jpg">
<img src="default_img.jpg" alt="avatar">
</picture>
Copy the code
This tag is typically used for reactive elements and allows for more flexibility in adjusting image resources. If the browser does not support this property, the image of the element will also be displayed.
10. Oncontextmenu property: Disable the right click
When we set the onContextMenu property on an element, right click is disabled. If you set this property to the body element, the entire page is disabled. Right click:
<p oncontextmenu="return false">Hello</p>
<body oncontextmenu="return false">.</body>
Copy the code
11. Input tag: color picker
The input tag is an element that supports many types. We can define the input as a color picker:
<input type="color" id="color-picker" name="color-picker" value="#e66465">
Copy the code
You can set the initial value of the color selector through value, or you can get the color of the color selector through the value property.
12. Base TAB: Open in a new TAB
We can set the target attribute of the base element to _black so that when the user clicks on the link, it always opens in a new TAB. This can be useful if you want to prevent users from accidentally leaving a page.
<head>
<base target="_blank">
</head>
<div>
<a href="https://www.baidu.com/">The baidu</a>
</div>
Copy the code
13. Placeholder style
Placeholder text can be set using the placeholder property:
<inputType =" placeholder "placeholder=" placeholder" />Copy the code
You can change the style of the placeholder text using the :: PLACEHOLDER CSS selector:
::placeholder {
color: # 210065;
opacity: 0.7;
font-size: 16px;
}
Copy the code