Loading shaders from HTML script tags

From webglcookbook
Jump to: navigation, search

This code (originally by Vladimir Vukićević) allows you to load shaders from HTML script tags like this:

<script id="shader-fs" type="x-shader/x-fragment">
  void main(void) {
    gl_FragColor = vec4(1, 1, 1, 1);
  }
</script>

Here's the code:

 function getShader(gl, id) {
   var shaderScript = document.getElementById(id);
   if (!shaderScript) {
     return null;
   }
   var str = "";
   var k = shaderScript.firstChild;
   while (k) {
     if (k.nodeType == 3) {
       str += k.textContent;
     }
     k = k.nextSibling;
   }
   var shader;
   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);
   gl.compileShader(shader);
   if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
     alert(gl.getShaderInfoLog(shader));
     return null;
   }
   return shader;
 }

Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox