Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Loading in WebGL Shaders

    Keith PetersKeith Peters

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



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    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.