I'm ramping up on WebGL and was wondering what is the best way to specify my vertex and fragment shaders.

Looking at some tutorials, the shaders are embedded directly in the HTML. (And referenced via an ID.) For example:

<script id="shader_1-fs" type="x-shader/x-fragment"> 
  precision highp float;
  void main(void) {
    // ... 

<script id="shader_1-vs" type="x-shader/x-vertex"> 
  attribute vec3 aVertexPosition;

  uniform mat4 uMVMatrix;
  // ...

My question is, is it possible to have my shaders referenced in a separate file? (Ideally as plain text.) I presume this is straight forward in JavaScript. Is there essentially a way to do this:

var shaderText = LoadRemoteFileOnSever('/shaders/shader_1.txt');

1 Answer 1


Yes, it's simple. You can just make an AJAX request to the file, and pass the code to WebGL's shaderSource function.

  • \$\begingroup\$ Yes. Note that if you use XMLHttpRequest asynchronously, then you'll need to wait until the data are loaded before calling .shaderSource. A game with lots of assets probably needs to do this with lots of images and other things as well, so you can combine them all into the same code which waits for multiple load events to complete. That's what I did (with images and sounds, not shaders). \$\endgroup\$
    – MarkR
    Commented Jan 1, 2013 at 11:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .