Browser - Compatibility Detection

Aus Wikizone
Version vom 11. Februar 2019, 15:11 Uhr von 93.208.103.149 (Diskussion)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

Browser JavaScript Kompatibilität testen[Bearbeiten]

https://www.quirksmode.org/js/support.html

Der Trick ist immer auf Arrays oder Objekte zu testen nicht auf Funktionen. Wenn eine Funktion nicht existiert gibt es eine Fehlermeldung.

Object detection - Yes Instead, we simply look if the browser supports the object (method, array or property) we want to use. Let’s continue with the mouseover example. This script relies on the document.images array, so first and foremost we'll have to detect if the browser supports it. This is done by

if (document.images)
{
	do something with the images array
}

Now you have a fail safe method of seeing if any browser can handle mouseovers. The if-statements checks if the array document.images exists. If it does (document.images) is true and the script is executed. If the images array doesn't exist it becomes false and the script is not executed.

Another common detect is for window.focus. This is a method (a command by which you tell JavaScript to do something for you). If we want to use the method, we'll have to check first if the browser supports it.

Note the correct way of doing this: you ask for the method without brackets. This code

if (window.focus)

means: "If the focus method is supported", while this code

if (window.focus())

means: "If you can put the focus on the window" and assumes that focus is supported. If it isn't, this line of code creates errors. The brackets () actually execute the focus command, which is not what we want in this case. So we check it without the brackets (see if it exists) and only when the browser passes the check we actually execute the command by adding brackets:

if (window.focus) window.focus()

Browser Feature Detection Snippets[Bearbeiten]