GLSL ES 1.00 and 3.00 in WebGL

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A WebGL context accepts shaders written in one of two dialects of the OpenGL ES Shading Language. WebGL 1.0 (OpenGL ES 2.0) understands GLSL ES 1.00. WebGL 2.0 (OpenGL ES 3.0) understands GLSL ES 3.00, written with a #version 300 es line, and also still compiles GLSL ES 1.00 shaders. The two look alike but are not source compatible: the keywords for shader inputs and outputs changed, the texture functions were renamed, and a lot that was forbidden or optional in 1.00 became ordinary. Both dialects are the web variant of the same family as desktop GLSL, so most of what you know carries over.

The facts were checked in November 2026 against the GLSL ES 1.00 and 3.00 specifications, the WebGL 1.0 and 2.0 specifications (editor’s drafts of June 2026) and the MDN documentation. The page covers GLSL ES 1.00 revision 17 and GLSL ES 3.00 revision 6, which are the revisions WebGL is defined against; WebGL 2 does not expose the newer OpenGL ES 3.1 and 3.2 shader features. Shaders run in every browser with WebGL, which for WebGL 2 means Chrome 56, Firefox 51, Edge 79 and Safari 15 or later. The examples are plain HTML and JavaScript with no library and run from a local static server.

In the Bookshelf raw WebGL track this page supports the step after the textured cover quad: the lit, rotating book that needs a normal, a light vector and a texture sample. Those shaders are written once in the portable form shown here and reused on the lighting page. The pipeline the shaders plug into is in The WebGL Rendering Pipeline; the vertex data they consume is in Buffers, Attributes, Uniforms and VAOs. For the same family of dialects on desktop, Android and iOS, see GLSL ES and Portability and Graphics, Canvas and OpenGL ES on Android; for the language in general, The GLSL Language and Shading Languages Landscape.

Two dialects, one decision

Choosing a dialect means choosing the context type, because a context only accepts what its OpenGL ES version defines:

Context Accepts Version line Typical reason

getContext('webgl') (WebGL 1)

GLSL ES 1.00

none, or #version 100

Support for very old devices, or code that must stay compatible with older libraries

getContext('webgl2') (WebGL 2)

GLSL ES 3.00 and GLSL ES 1.00

#version 300 es as the first line, or none for 1.00

Everything new: it is available in about 97 percent of browsers

A single program must be written in a single version. A vertex shader of version 100 cannot be linked with a fragment shader of 300 es, and the link fails with a message about mismatched versions. In a WebGL 2 context you can keep using 1.00 shaders, but new code should use 3.00: it unlocks integers, uniform blocks, texelFetch, instancing built-ins, multiple colour outputs and dynamic loops.

The version line has to be the very first thing in the shader source, with no blank line or space before it. The most common GLSL ES 3.00 error is a template literal that starts with a newline:

// Wrong: the string starts with a newline, so the first line is not "#version 300 es"
const bad = `
#version 300 es
void main() { gl_Position = vec4(0.0); }`;

// Right: the backtick is immediately followed by the version directive
const good = `#version 300 es
void main() { gl_Position = vec4(0.0); }`;

The keyword map

A three-column table mapping each concept to its GLSL ES 1.00 spelling and its GLSL ES 3.00 spelling
Figure 1. The same shader written for both dialects

The vertex shader of the Bookshelf cover, in both dialects, shows nearly every difference at once.

// GLSL ES 1.00 vertex shader (WebGL 1; also accepted by WebGL 2)
attribute vec2 aPosition;
attribute vec2 aUv;
varying vec2 vUv;
uniform float uAspect;

void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition.x / uAspect, aPosition.y, 0.0, 1.0);
}
#version 300 es
// GLSL ES 3.00 vertex shader (WebGL 2 only)
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aUv;
out vec2 vUv;
uniform float uAspect;

void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition.x / uAspect, aPosition.y, 0.0, 1.0);
}
// GLSL ES 1.00 fragment shader
precision mediump float;
varying vec2 vUv;
uniform sampler2D uCover;

void main() {
  gl_FragColor = texture2D(uCover, vUv);
}
#version 300 es
// GLSL ES 3.00 fragment shader
precision mediump float;
in vec2 vUv;
uniform sampler2D uCover;
out vec4 outColor;

void main() {
  outColor = texture(uCover, vUv);
}

The rules behind the map:

  • attribute becomes in in the vertex shader. varying becomes out in the vertex shader and in in the fragment shader.

  • The fragment colour is no longer the built-in gl_FragColor; you declare one or more user out variables.

  • The sampling functions lost their type suffix: texture2D and textureCube are both texture, chosen by the sampler type. texture2DProj is textureProj, texture2DLodEXT is textureLod.

  • A fragment shader still has no default float precision in either version; you must declare one (see the next sections).

  • Names beginning with gl_ are reserved for built-ins. WebGL also reserves identifiers beginning with webgl_ and _webgl_; a shader that declares one does not load.

What GLSL ES 3.00 adds

The new language is the bigger of the two changes. These are the additions that are most useful in a WebGL 2 program.

Area GLSL ES 1.00 GLSL ES 3.00

Integers

int with no bitwise operators; loops and indexing restricted

int and uint (32 bits for highp), bitwise operators, uvec and ivec types, integer textures

Loops and indexing

The restrictions of the specification’s appendix A: for loops with constant bounds, constant-index expressions for many arrays

Dynamic loops, while, do, switch, arbitrary array indexing (with undefined results out of range)

Matrices

mat2, mat3, mat4 only

Also mat2x3, mat2x4, mat3x2, mat3x4, mat4x2, mat4x3 and functions transpose, inverse, determinant and outerProduct

Textures

texture2D, textureCube, derivative and LOD access via extensions

texture, textureLod, textureGrad, textureProj, textureOffset, texelFetch (no sampler), textureSize; 3D, 2D-array, shadow and integer samplers

Built-in functions

The 1.00 set

Adds round, roundEven, trunc, isnan, isinf, sinh and the other hyperbolics, floatBitsToInt and its inverses, packHalf2x16 and the other pack functions, and more

Derivatives

dFdx, dFdy, fwidth need OES_standard_derivatives

Always available in fragment shaders

Inputs and outputs

attribute, varying, gl_FragColor, gl_FragData (extension)

in, out, layout(location = n), interpolation qualifiers smooth, flat, centroid

Uniforms

Single uniforms only

Uniform blocks with layout(std140), backed by buffers, shared between programs

Vertex and fragment built-ins

gl_Position, gl_PointSize, gl_FragCoord, gl_FrontFacing, gl_PointCoord

Adds gl_VertexID, gl_InstanceID, and gl_FragDepth without an extension

Features of OpenGL ES 3.1 and 3.2 shaders, such as compute shaders, shader storage buffers, image load and store, geometry and tessellation shaders, are not in WebGL 2, because the specification is based on OpenGL ES 3.0. Compute in the browser comes with WebGPU (see WebGPU Overview and Comparison).

Extensions in the shader

An extension that adds shader features has two sides: a JavaScript object you request with gl.getExtension, and an #extension directive in the GLSL source that enables the symbols. In WebGL 1 you must do both.

JavaScript name Shader directive Adds in GLSL ES 1.00 In WebGL 2

OES_standard_derivatives

#extension GL_OES_standard_derivatives : enable

dFdx, dFdy, fwidth

core; getExtension returns null, so remove the directive

EXT_shader_texture_lod

#extension GL_EXT_shader_texture_lod : enable

texture2DLodEXT and friends

core as textureLod

EXT_frag_depth

#extension GL_EXT_frag_depth : enable

gl_FragDepthEXT

core as gl_FragDepth

WEBGL_draw_buffers

#extension GL_EXT_draw_buffers : require

gl_FragData[i] for several outputs

core with layout(location = i) out

Detection and fallbacks are described in Extensions.

Precision qualifiers

Shaders on phones and tablets often run in reduced precision to save power. GLSL ES lets you say how much you need with lowp, mediump and highp, and the specification guarantees minimums rather than exact formats.

A table of lowp, mediump and highp with the float range, float precision, integer range and typical use of each
Figure 2. Precision qualifiers and their guaranteed minimums
Where Default for float Default for int Samplers

Vertex shader

highp

highp

lowp

Fragment shader

none: the shader does not compile without a declaration

mediump

lowp

The usual first lines of a fragment shader are therefore:

precision mediump float;        // default for every float in the file, unless a variable says otherwise
precision highp int;            // optional: wider integers for ids and counters

Choosing: mediump is enough for texture coordinates in small textures, colours, normals and light directions. highp is needed for world-space positions, large texture coordinates, depth, anything that is accumulated over time, and any computation with fract of big numbers. A frequent source of "works on my desktop but flickers on a phone" bugs is a mediump position or time value, because many desktop GPUs treat every qualifier as 32-bit float and hide the problem.

Is highp available in a fragment shader? In GLSL ES 3.00 it is mandatory. In GLSL ES 1.00 it is optional, and a WebGL 1 program on an old device may not have it. The shader can test the preprocessor macro, and JavaScript can query the real formats:

function describePrecision(gl) {
  const types = [
    ['vertex', gl.VERTEX_SHADER],
    ['fragment', gl.FRAGMENT_SHADER],
  ];
  const kinds = [
    ['lowp float', gl.LOW_FLOAT], ['mediump float', gl.MEDIUM_FLOAT], ['highp float', gl.HIGH_FLOAT],
    ['lowp int', gl.LOW_INT], ['mediump int', gl.MEDIUM_INT], ['highp int', gl.HIGH_INT],
  ];
  const lines = [];
  for (const [stage, shaderType] of types) {
    for (const [name, precisionType] of kinds) {
      const f = gl.getShaderPrecisionFormat(shaderType, precisionType);
      // rangeMin and rangeMax are the log2 of the smallest and largest magnitudes; precision is the number of mantissa bits
      lines.push(`${stage} ${name}: range 2^${f.rangeMin} .. 2^${f.rangeMax}, precision ${f.precision} bits`);
    }
  }
  return lines.join('\n');
}
// A precision of 0 for HIGH_FLOAT in the fragment stage means highp is not supported there (possible in WebGL 1)
// GLSL ES 1.00: use highp where the device supports it, otherwise fall back
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif

A precision qualifier on a variable, parameter or return type overrides the default, and the precision of an expression is that of the highest operand, so mixing a highp uniform with mediump varyings gives highp arithmetic. Precision also applies to samplers: uniform highp sampler2D uCover; matters for float or integer textures. Integer varyings and values converted between precisions follow the specification’s rules; do not rely on overflow behaviour.

Interpolation qualifiers

In GLSL ES 1.00 every varying is perspective-correct, smooth and floating point. GLSL ES 3.00 lets you choose, and requires the choice to match in both stages.

Two triangles filled with colour: smooth blends three vertex colours, flat uses the value of the last vertex; a box explains centroid sampling
Figure 3. How smooth and flat interpolation fill a triangle
Qualifier Behaviour Typical use

smooth (default)

Perspective-correct blend of the three vertex values

Colours, texture coordinates, normals, positions

flat

No interpolation: each fragment receives the value of the provoking vertex, the last vertex of the triangle in OpenGL ES 3.0

Integer ids, material indices, per-primitive data; required for integer varyings and inputs

centroid

Interpolated like smooth, but evaluated inside the primitive, never outside it when multisampling is active

Fixes artefacts at the edges of multisampled textured geometry

There is no noperspective qualifier in GLSL ES. Integer types, including int and uint vectors, must be flat. The next pair draws nine Bookshelf spines from one instanced draw call, giving each a colour from its instance number; the id travels as a flat integer, so the fragment shader receives the exact value without any blending.

#version 300 es
// vertex shader: nine instances laid out along x, no instance buffer needed
layout(location = 0) in vec2 aPosition;     // a unit rectangle, x and y from -1 to 1
flat out int vBook;
out vec2 vLocal;

void main() {
  float slot = float(gl_InstanceID);
  vec2 centre = vec2(-0.8 + slot * 0.2, 0.0);
  gl_Position = vec4(centre + aPosition * vec2(0.08, 0.6), 0.0, 1.0);
  vBook = gl_InstanceID;
  vLocal = aPosition;
}
#version 300 es
precision mediump float;
flat in int vBook;
in vec2 vLocal;
out vec4 outColor;

void main() {
  vec3 palette[3] = vec3[3](vec3(0.60, 0.27, 0.10), vec3(0.15, 0.30, 0.55), vec3(0.20, 0.45, 0.28));
  vec3 colour = palette[vBook % 3];               // dynamic indexing is allowed in GLSL ES 3.00
  float shade = 0.75 + 0.25 * vLocal.x;           // a smooth varying in the same shader
  outColor = vec4(colour * shade, 1.0);
}
// Draw the nine instances (the vertex array holds one four-vertex triangle strip rectangle)
gl.bindVertexArray(spineVao);
gl.useProgram(spineProgram);
gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, 9);

Layout qualifiers and linking

Inputs and outputs have to be bound to numbers so that the JavaScript side can find them. GLSL ES 1.00 has no layout syntax: you either let the linker pick and ask with gl.getAttribLocation(program, 'aPosition'), or you call gl.bindAttribLocation(program, 0, 'aPosition') before gl.linkProgram, which takes effect at link time. GLSL ES 3.00 adds layout(location = n):

  • layout(location = n) in on vertex shader inputs fixes the attribute slot in the source, so a VAO can be shared among programs.

  • layout(location = n) out on fragment shader outputs picks the colour attachment, which is how WebGL 2 writes to several render targets. There is no bindFragDataLocation in WebGL, so with several outputs the layout qualifier is the only way.

  • Layout locations are not allowed on varyings between the vertex and fragment shader in 3.00; the names must match instead.

  • Uniform blocks use layout(std140); their binding point is set from JavaScript with gl.uniformBlockBinding. Layouts are in Buffers, Attributes, Uniforms and VAOs.

The names of varyings must match between stages, with the same type, precision (a fragment in may use a different precision than the vertex out, within the rules), and interpolation qualifier. A mismatch is reported by the linker, never earlier, so always read the program info log.

A runnable page that drives both dialects

The page below paints a patterned book spine in a WebGL 1 or WebGL 2 context, selected by the query string. Open index.html for WebGL 2 and index.html?webgl=1 for WebGL 1. The same attribute slots are fixed with bindAttribLocation for both dialects, so the JavaScript side is identical, and the sources show the keyword map in practice.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bookshelf: one shader, two dialects</title>
<style>
  html, body { margin: 0; height: 100%; background: #20242c; color: #e5e7eb; font: 14px sans-serif; }
  canvas { width: 100%; height: 100%; display: block; }
  #info { position: fixed; left: 8px; top: 8px; padding: 4px 8px; background: rgba(0, 0, 0, 0.5); }
</style>
</head>
<body>
<canvas id="gl"></canvas>
<div id="info"></div>
<script type="module">
const canvas = document.getElementById('gl');
const wantWebGL1 = new URLSearchParams(location.search).get('webgl') === '1';
const gl = wantWebGL1 ? canvas.getContext('webgl') : canvas.getContext('webgl2');
if (!gl) throw new Error('The requested WebGL version is not available');
const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;

document.getElementById('info').textContent =
  `${gl.getParameter(gl.VERSION)} | ${gl.getParameter(gl.SHADING_LANGUAGE_VERSION)}`;

// Both dialects of the same shaders; the fragment shader paints gold bands on leather with a moving phase
const sources = isWebGL2 ? {
  vertex: `#version 300 es
in vec2 aPosition;
in vec2 aUv;
out vec2 vUv;
uniform float uAspect;
void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition.x / uAspect, aPosition.y, 0.0, 1.0);
}`,
  fragment: `#version 300 es
precision mediump float;
in vec2 vUv;
uniform float uPhase;
out vec4 outColor;
void main() {
  float band = step(0.5, fract(vUv.y * 6.0 + uPhase));
  vec3 colour = mix(vec3(0.42, 0.17, 0.06), vec3(0.93, 0.78, 0.30), band * step(0.15, vUv.x) * step(vUv.x, 0.85));
  outColor = vec4(colour, 1.0);
}`,
} : {
  vertex: `attribute vec2 aPosition;
attribute vec2 aUv;
varying vec2 vUv;
uniform float uAspect;
void main() {
  vUv = aUv;
  gl_Position = vec4(aPosition.x / uAspect, aPosition.y, 0.0, 1.0);
}`,
  fragment: `precision mediump float;
varying vec2 vUv;
uniform float uPhase;
void main() {
  float band = step(0.5, fract(vUv.y * 6.0 + uPhase));
  vec3 colour = mix(vec3(0.42, 0.17, 0.06), vec3(0.93, 0.78, 0.30), band * step(0.15, vUv.x) * step(vUv.x, 0.85));
  gl_FragColor = vec4(colour, 1.0);
}`,
};

function compile(type, source) {
  const shader = gl.createShader(type);
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    const log = gl.getShaderInfoLog(shader);
    gl.deleteShader(shader);
    throw new Error(`${type === gl.VERTEX_SHADER ? 'Vertex' : 'Fragment'} shader failed:\n${log}`);
  }
  return shader;
}

const program = gl.createProgram();
gl.attachShader(program, compile(gl.VERTEX_SHADER, sources.vertex));
gl.attachShader(program, compile(gl.FRAGMENT_SHADER, sources.fragment));
gl.bindAttribLocation(program, 0, 'aPosition');      // same slots in both dialects, set before linking
gl.bindAttribLocation(program, 1, 'aUv');
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program));
const uAspect = gl.getUniformLocation(program, 'uAspect');
const uPhase = gl.getUniformLocation(program, 'uPhase');

// x, y, u, v for a triangle strip: a tall, narrow book spine
const data = new Float32Array([
  -0.25, -0.8, 0, 0,
   0.25, -0.8, 1, 0,
  -0.25,  0.8, 0, 1,
   0.25,  0.8, 1, 1,
]);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);

// WebGL 1 has no vertex array objects without an extension, so the pointers are set up each frame in both modes
function bindAttributes() {
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  gl.enableVertexAttribArray(0);
  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);
  gl.enableVertexAttribArray(1);
  gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);
}

function frame(time) {
  const w = Math.max(1, Math.round(canvas.clientWidth * devicePixelRatio));
  const h = Math.max(1, Math.round(canvas.clientHeight * devicePixelRatio));
  if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h; }
  gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  gl.clearColor(0.13, 0.14, 0.17, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.useProgram(program);
  bindAttributes();
  gl.uniform1f(uAspect, gl.drawingBufferWidth / gl.drawingBufferHeight);
  gl.uniform1f(uPhase, time * 0.0003);
  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
</script>
</body>
</html>

Porting a GLSL ES 1.00 shader to 3.00

Most of the port is mechanical. The following steps, in order, convert almost every WebGL 1 shader:

  1. Add #version 300 es as the first line.

  2. In the vertex shader, rename attribute to in and varying to out. In the fragment shader, rename varying to in.

  3. In the fragment shader declare an output, for example out vec4 outColor;, and replace every gl_FragColor with it. Replace each gl_FragData[i] with its own layout(location = i) out.

  4. Rename texture2D, textureCube, texture2DProj and texture2DLodEXT to texture, textureProj and textureLod.

  5. Delete #extension lines for the extensions that became core (see the table above). Rename gl_FragDepthEXT to gl_FragDepth.

  6. If a variable is called texture, round, sample, in, out, flat, smooth or any other newly reserved word, rename it.

  7. Fix integer code that relied on 1.00 limits and consider now-legal dynamic indexing.

The first five steps can be automated for simple shaders. The helper below converts a 1.00 vertex or fragment shader to 3.00; treat it as a starting point, because regular expressions do not understand GLSL scoping.

/**
 * Convert simple GLSL ES 1.00 source to GLSL ES 3.00.
 * stage is 'vertex' or 'fragment'. Throws on constructs it cannot translate.
 */
export function glsl100To300(source, stage) {
  if (/\b(float|vec[234]|int|sampler\w+)\s+texture\b/.test(source)) {
    throw new Error('A variable called "texture" must be renamed before conversion');
  }
  let out = source
    .replace(/^\s*#version\s+100[^\n]*\n/, '')
    .replace(/^\s*#extension\s+GL_(OES_standard_derivatives|EXT_shader_texture_lod|EXT_frag_depth)[^\n]*\n/gm, '')
    .replace(/\btexture2DProj\b/g, 'textureProj')
    .replace(/\btexture2DLodEXT\b/g, 'textureLod')
    .replace(/\btexture2D\b/g, 'texture')
    .replace(/\btextureCube\b/g, 'texture')
    .replace(/\bgl_FragDepthEXT\b/g, 'gl_FragDepth');

  if (stage === 'vertex') {
    out = out.replace(/\battribute\b/g, 'in').replace(/\bvarying\b/g, 'out');
  } else {
    if (/\bgl_FragData\b/.test(out)) {
      throw new Error('gl_FragData needs hand-written layout(location = n) out declarations');
    }
    out = out.replace(/\bvarying\b/g, 'in').replace(/\bgl_FragColor\b/g, 'outColor');
    // The output must be declared after the precision statement that precedes it, or with its own precision
    if (!/precision\s+\w+\s+float\s*;/.test(out)) throw new Error('Declare a default float precision first');
    out = out.replace(/(precision\s+\w+\s+float\s*;)/, '$1\nout highp vec4 outColor;');
  }
  return '#version 300 es\n' + out;
}

// Example
const fragment100 = `precision mediump float;
varying vec2 vUv;
uniform sampler2D uCover;
void main() { gl_FragColor = texture2D(uCover, vUv); }`;
console.log(glsl100To300(fragment100, 'fragment'));

The reverse direction, 3.00 to 1.00, cannot be automated in general because of integers, uniform blocks and texelFetch; keep a 1.00 fallback only if you really need WebGL 1, and write the shared parts once in a snippet that both dialects include. A small preamble that maps the keywords is a common alternative to maintaining two copies:

// preamble for GLSL ES 3.00: lets 1.00-style source compile unchanged
#define attribute in
#define varying in
#define texture2D texture
#define textureCube texture

Use one preamble per stage (for the vertex stage varying must map to out), and build the final source by concatenating the version line, the preamble and the shared body.

What 1.00 restricts that 3.00 allows

Appendix A of the GLSL ES 1.00 specification defines the minimum a WebGL 1 implementation must support, and WebGL 1.0 requires shaders to stay inside it: shaders written for other versions or for desktop GLSL must not load. The restrictions that surprise people:

  • while and do-while loops are not allowed, and for loops need a constant loop count that the compiler can determine.

  • In a fragment shader, arrays and matrices can be indexed only with constant-index expressions; in a vertex shader, dynamic indexing is only guaranteed for uniforms.

  • There is no integer bit manipulation, no switch, and % does not exist.

  • highp in fragment shaders is optional, mediump int may cover only the range -1024 to 1024.

  • No matrix inverse or transpose, no round and trunc.

  • There is a limit on the total instruction count that is device-specific and not queryable.

Many of these are lifted in GLSL ES 3.00, but not everything: GLSL ES 3.00 still has no recursion, no pointers, no dynamic memory and no implementation-independent limit on uniforms, so always consult MAX_VERTEX_UNIFORM_VECTORS, MAX_FRAGMENT_UNIFORM_VECTORS and MAX_VARYING_VECTORS (see the pipeline page for minimum values).

Seeing what the browser compiled

WebGL implementations do not pass your GLSL to the driver untouched. Chrome, Firefox and Safari validate and translate it (Chrome and Firefox use ANGLE’s shader translator), which rewrites it for Direct3D, Metal, Vulkan or desktop OpenGL. When a shader behaves differently on one machine, the translated text helps. The WEBGL_debug_shaders extension returns it, for debugging only, and the extension may be unavailable in some browsers.

function logTranslatedSource(gl, shader) {
  const ext = gl.getExtension('WEBGL_debug_shaders');
  if (!ext) {
    console.info('WEBGL_debug_shaders is not available here');
    return;
  }
  // call after gl.compileShader succeeded
  console.log(ext.getTranslatedShaderSource(shader));
}

Always read gl.getShaderInfoLog after compiling and gl.getProgramInfoLog after linking. Error line numbers refer to your source string, which is why starting a template literal with a newline (and shifting every line by one) makes logs confusing. Expensive programs can take hundreds of milliseconds to compile and link on some platforms, so the KHR_parallel_shader_compile extension lets the browser compile in the background while you poll:

const parallel = gl.getExtension('KHR_parallel_shader_compile');

function whenProgramReady(program) {
  return new Promise((resolve, reject) => {
    function check() {
      if (parallel && !gl.getProgramParameter(program, parallel.COMPLETION_STATUS_KHR)) {
        requestAnimationFrame(check);              // still compiling, keep rendering other things
        return;
      }
      if (gl.getProgramParameter(program, gl.LINK_STATUS)) {
        resolve(program);
      } else {
        reject(new Error(gl.getProgramInfoLog(program)));
      }
    }
    check();
  });
}
// Call gl.linkProgram(program) for every program first, then await whenProgramReady for each

For validating shaders outside the browser, Khronos publishes a reference compiler front end, glslang, whose glslangValidator command-line tool accepts #version 300 es sources; see GLSL ES and Portability for a workflow. The validator and the browser translator can differ in what they accept, so the browser result is final.

Common mistakes

  • Starting the shader string with a blank line or indentation before #version 300 es.

  • Linking a vertex shader of one version with a fragment shader of another.

  • Forgetting precision mediump float; in a fragment shader, which fails to compile in both versions.

  • Using gl_FragColor or texture2D in a 3.00 shader, or texture and in in a 1.00 shader.

  • Declaring an integer varying without flat, or a flat qualifier on only one stage.

  • Calling gl.bindAttribLocation after gl.linkProgram, which has no effect until the next link.

  • Requesting OES_standard_derivatives in a WebGL 2 context. The call returns null because derivatives are built in; the extension directive in a 3.00 shader is also not needed.

  • Assuming the compile succeeded: compileShader never throws, and a failed shader only shows up in the status and the log.

  • Trusting mediump precision on desktop. Test on a phone or force precision emulation in your tooling.

  • Naming identifiers with webgl_ or _webgl_ prefixes, which WebGL reserves.

  • Dynamic indexing of uniform arrays in GLSL ES 1.00 fragment shaders (not allowed there).

Performance notes

  • Compile and link asynchronously where the extension exists, and warm up programs while a loading screen is shown.

  • Precision qualifiers matter on mobile GPUs: mediump arithmetic can be faster on some mobile GPUs. The qualifiers have little effect on most desktop GPUs.

  • Branches on uniforms are cheap; branches on varying or texture data may run both sides because pixels in a quad execute together.

  • Reduce varyings (each vec4 slot costs interpolation bandwidth) and pack two vec2 values into one vec4 when you can.

  • Integer arithmetic and bit operations in 3.00 are efficient, but integer division and modulo are slower than float operations on some GPUs.

  • Use uniform blocks to update many uniforms with one buffer upload instead of dozens of gl.uniform* calls.

  • Keep the number of distinct programs small and sort draws by program; switching programs is a state change.

Where older material is outdated

Older statement Today

PAR chapter 3 introduces shaders as GLSL ES 1.00 only, with attribute, varying, gl_FragColor and texture2D, plus the loop and indexing restrictions of appendix A.

Still valid for WebGL 1. WebGL 2 uses in, out, a declared fragment output and texture, and lifts most restrictions. New code starts with #version 300 es.

LTJ chapter 4 and chapter 11 and TCB chapter 5 write custom shaders for three.js r69 with attribute, varying, gl_FragColor and texture2D.

three.js WebGLRenderer has used WebGL 2 only since r163 and still accepts 1.00-style ShaderMaterial source and adapts it; the glslVersion option selects THREE.GLSL3 for 3.00 source. ShaderMaterial does not work with WebGPURenderer, which uses TSL. See Custom Shaders in three.js and WebGPURenderer and TSL.

Books use "experimental-webgl" and extension checks done once and kept in a global.

getContext('webgl2'), and getExtension per feature; many former extensions are core in WebGL 2.

Guides say shader code cannot be inspected once the browser has compiled it.

WEBGL_debug_shaders returns the translated source for debugging; the info logs remain the first tool.

Guides claim highp is always available in fragment shaders, or never.

It is mandatory in GLSL ES 3.00 and optional in 1.00; use getShaderPrecisionFormat or GL_FRAGMENT_PRECISION_HIGH.

Recent changes

When Change

January 2017 onward

WebGL 2.0 shipped with GLSL ES 3.00 in Chrome 56 and Firefox 51, in Edge 79 and in Safari 15 (2021).

three.js r163 (2024)

WebGLRenderer dropped WebGL 1, so ShaderMaterial source always compiles as GLSL ES 3.00 on that renderer.

June 2026

The WebGL 1.0 and 2.0 specification editor’s drafts were last updated. WebGL 2.0 is still defined against GLSL ES 3.00; OpenGL ES 3.1 and 3.2 shader features are not part of it.

See it in