Home Web Front-end JS Tutorial JavaScript feature detection is not browser detection_javascript tips

JavaScript feature detection is not browser detection_javascript tips

May 16, 2016 pm 06:36 PM
javascript Browser detection

I have roughly translated part of the article. There may be some misunderstandings. Please correct me. It’s worth mentioning that the debate in the comments section is also worth reading.

Feature Detection
At first, front-end engineers strongly opposed browser detection. They believed that methods like user-agent sniffing were very bad because it was not a This is future-proof code that cannot adapt to new browser versions. A better approach is to use feature detection, like this:

Copy the code The code is as follows:

if (navigator.userAgent.indexOf("MSIE 7") > -1){
//do something
}

A better way is:
Copy code The code is as follows:

if(document.all){
//do something
}

The two methods are not the same. The former is to detect the special name and version of the browser; the latter is to detect the characteristics of the browser. UA sniffing can accurately obtain the type and version of the browser (at least the browser type), while feature detection is to determine whether the browser owns a certain object or supports a certain method. Note that these two are completely different.
Because feature detection depends on which browsers support it, tedious confirmation work is required when a new version of the browser appears. For example, when the DOM standard first appeared, not all browsers supported the getElementById() method, so the initial code might look like this:
Copy code The code is as follows:

if(document.getElementById){ //DOM
element = document.getElementById(id);
} else if (document.all) { //IE
element = document.all[id];
} else if (document.layers){ //Netscape < 6
element = document.layers[id];
}

This is a good example of feature detection. The highlight is that when other browsers start to support the getElementById() method, there is no need to modify the code.
Mixed method
Later, the front-end engineers considered an improved way of writing, and the code changed like this:
Copy the code The code is as follows :

//AVOID!!!
if (document.all) { //IE
id = document.uniqueID;
} else {
id = Math .random();
}

The problem with this code is to determine whether it is IE by detecting the document.all attribute. When identifying IE, it is safe to assume that the private document.uniqueID property is used. However, what is currently done is only to determine whether document.all is supported, not to identify whether the browser is IE. Just supporting document.all does not mean that document.uniqueID is available.
Later people began to write like this, replacing the above line with the following line:
var isIE = navigator.userAgent.indexOf("MSIE") > -1;
//The following line replaced the above line
var isIE = !!document.all; These changes indicate that everyone has a misunderstanding about "Don't use UA sniffing" - the browser's detailed information is no longer detected, but is inferred through feature support. This method of detecting based on browser features is very bad.
Later, the front-ends discovered that document.all was not reliable, and a better way to detect IE became:
var isIE = !!document.all && document.uniqueID; This implementation went astray. Not only does it take time and effort to identify the feature support added by the browser, but it is also impossible to be sure that other browsers will start to support the same features.
If you think code like this is not widely used, take a look at this code snippet from an older version of Mootools:
Copy code The code is as follows:

//from MooTools 1.1.2
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if ( document.getBoxObjectFor != null || window.mozInnerScreenX != null) window.gecko = true;

Note how it uses feature detection. I can point out a series of problems, such as mistaking ie8 for ie7 by detecting window.ie.
Aftermath
With the rapid development of browsers, using feature detection has become increasingly difficult and unreliable. But Mootools 1.2.4 still uses this method, for example: getBoxObjectFor().
Copy code The code is as follows:

//from MooTools 1.2.4
var Browser = $merge({
Engine: {name: 'unknown', version: 0},
Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match( /mac|win|linux/i) || ['other'])[0].toLowerCase()},
Features: {xpath: !!(document.evaluate), air: !!(window.runtime ), query: !!(document.querySelector)},
Plugins: {},
Engines: {
presto: function(){
return (!window.opera) ? false : ( (arguments.callee.caller) ? 960: ((document.getElementsByClassName) ? 950: 925)); ((window.XMLHttpRequest)? ((document.querySelectorAll)? 6:5):4); Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419); mozInnerScreenX == null) ? false: ((document.getElementsByClassName) ? 19 : 18); How to do it?
Feature detection is a method that should be avoided, although direct feature detection is a good method and can meet the needs in most cases. Generally, it is enough to know whether this feature has been implemented before testing, without considering the relationship between them.
I'm not saying never use browser feature detection but rather UA sniffing, because I believe it still has many uses, however I don't believe it has many legitimate uses. If you are considering UA sniffing, please implement this idea first: the only safe way is to target a specific version of a specific browser, and anything beyond that is unreliable - such as new browser versions. In fact, this is also a wise approach, because compared with forward compatibility with uncertain new versions, backward compatibility with old versions is the easiest way.
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles