This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Loading in WebGL Shaders

2:28 JavaScript lesson by

In this lesson we look at a better way of writing WebGL shaders - loading them in from script tags rather than concatenating JavaScript strings.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this lesson we look at a better way of writing WebGL shaders - loading them in from script tags rather than concatenating JavaScript strings.

As we'll soon be doing a lot more with shaders, let's figure out an easier way to write them rather than concatenating these JavaScript strings. A common way to do this is write the shaders in HTML script tags, and load them in via the DOM.

Go to copy in a script from the MDN Developer site that does just what we need. It's called getShader. It lets you pass in a script ID, and then finds that script element using getElementById.

It then loops through the text nodes, putting all the text into a variable called the source. Then it creates a shader using the type attribute of that script to determine if it should create a vertex shader or a fragment shader, and it adds the source to the shader and compiles it.

It then even tests to see if the compilation was successful by querying the compile status of the shader. If all was OK, it returns the compiled shader.

With that in place, we can go into the HTML and create two script tags. One will have an ID of shader-vs and a type of x-shader/x-vertex. That, obviously, will be our vertex shader. The fragment shader script will have an ID of shader-fs and a type of x-shader/x-fragment.

Now I can copy the code for the vertex shader, paste it in here, and clean it up a bit. Then I can do the same for the fragment shader. Now, this will be much easier to edit than a concatenated string.

Back in the createShaders function we can get rid of all this, and this, and this, and instead call getShader gl shader-vs for the vertex shader. The same for the fragment shader using the ID shader-fs.

That's a whole lot cleaner overall. We run it and everything still works. To verify, I'll change some of the values we're passing in and make sure that they get to the shader and get rendered.

Yes, it's definitely getting and compiling that shader code. Of course, you could do something beyond this such as storing your shader code in external files and using jQuery or something to load them in as text, and then create the shaders with that text. But the method we have here will do well enough for these lessons.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?