attachShader method

Attaches a WebGLShader object to a WebGLProgram object.




WebGLRenderingContext.attachShader(program, shader);


program [in]

Type: WebGLProgram

The WebGLProgram object created using the createProgram method.

shader [in]

Type: WebGLShader

The WebGLShader object to attach.

Return value

This method does not return a value.


WebGL errorDescription
  • If program isn't a program object.
  • If shader isn't a shader object.
  • If shader is already attached to program, or another shader object of the same type is already attached.
gl.INVALID_VALUEIf either program or shader isn't a value generated by WebGL.


A shader can be attached to a program before or after the code is loaded into the shader object and compiled. Only one shader object of each type can be attached to the same program object, but the same shader object can be attached to multiple program objects.

Both a vertex and a fragment shader are required in order to link the program.


This clip creates a program and attaches a vertex and a fragment shaders. See Get started with WebGL for more info.

function loadProgram(gl, vertexShader, fragmentShader)
  // create a progam object
  var program = gl.createProgram();

  // attach the two shaders 
  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);

  // link everything 

  // Check the link status
  var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  if (!linked) {

    // An error occurred while linking
    var lastError = gl.getProgramInfoLog(program);
    console.warn("Error in program linking:" + lastError);

    return null;

  // if all is well, return the program object
  return program;

See also