compileShader method

Compiles the GLSL shader source into binary data used by the WebGLProgram object.






shader [in]

Type: WebGLShader

An object that represents source code strings.

Return value

This method does not return a value.


When compiling shader source code, call getShaderParameter to get the status. getShaderParameter returns true if the source compiled successfully, or false if compilation failed. On failure, call getShaderInfoLog for the shader compiler's log. Errors are contained in the log.

WebGL errorDescription
  • shader isn't a WebGLShader object.
  • shader is not generated by WebGL.
gl.INVALID_OPERATIONThe shader compiler isn't supported.



The following example gets shader code from a <script> tag in an HTML document, and creates a fragment or vertex shader, and compiles it using the compileShader method. For more info on this example, see Get started with WebGL.

// Loads a shader from a script tag
// Parameters:
//   WebGL context
//   id of script element containing the shader to load
function getShader(gl, id) {
  var shaderScript = document.getElementById(id);

  // error - element with supplied id couldn't be retrieved
  if (!shaderScript) {
    return null;

  // If successful, build a string representing the shader source
  var str = "";
  var k = shaderScript.firstChild;
  while (k) {
    if (k.nodeType == 3) {
      str += k.textContent;
    k = k.nextSibling;

  var shader;

  // Create shaders based on the type we set
  //   note: these types are commonly used, but not required
  if (shaderScript.type == "x-shader/x-fragment") {
    shader = gl.createShader(gl.FRAGMENT_SHADER);
  } else if (shaderScript.type == "x-shader/x-vertex") {
    shader = gl.createShader(gl.VERTEX_SHADER);
  } else {
    return null;

  gl.shaderSource(shader, str);

  // Check the compile status, return an error if failed
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    return null;

  return shader;

See also