How to Detect WebGL Support Before Three.js

Before initializing a Three.js application, it is crucial to verify whether the user’s browser and hardware support WebGL. Detecting this compatibility beforehand prevents runtime crashes, avoids loading heavy 3D assets unnecessarily, and allows you to display a graceful fallback message to the user. This article provides straightforward methods to check for WebGL support using both native JavaScript and built-in Three.js utilities.

Method 1: Using the Native JavaScript API

The most direct way to check for WebGL support without loading external libraries is by creating an off-screen HTML5 <canvas> element and attempting to retrieve its WebGL context.

Here is a simple, reusable JavaScript function to perform this check:

function isWebGLAvailable() {
    try {
        const canvas = document.createElement('canvas');
        return !!(window.WebGLRenderingContext && 
            (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
    } catch (e) {
        return false;
    }
}

// Usage
if (isWebGLAvailable()) {
    // Initialize your Three.js scene here
    console.log("WebGL is supported. Initializing Three.js...");
} else {
    // Display a fallback message to the user
    console.error("WebGL is not supported on this browser or device.");
    document.body.innerHTML = '<div class="error">Your browser does not support WebGL. Please update your browser or device.</div>';
}

How It Works:

  1. Feature Detection: It first checks if window.WebGLRenderingContext exists in the browser.
  2. Context Creation: It attempts to initialize either the standard webgl context or the older experimental-webgl context (used by legacy browsers).
  3. Double Negation (!!): Converts the truthy context object or falsy null value into a strict boolean.

Method 2: Using the Three.js WebGL Utility

If you are already bundling Three.js in your project, you can use the official WebGL utility compatibility script provided by the library. This utility checks for WebGL support and can also generate a pre-styled error message for the user.

First, import the WebGL utility from the Three.js addons directory:

import WebGL from 'three/addons/capabilities/WebGL.js';

if (WebGL.isWebGLAvailable()) {
    // Initialize your Three.js scene here
    initThreeJSApp();
} else {
    // Retrieve the default Three.js error message element
    const warning = WebGL.getWebGLErrorMessage();
    // Append the warning to your container element
    document.getElementById('container').appendChild(warning);
}

Why Use the Three.js Utility?