Search code examples
javascriptthree.jswebglwebgl2

Loading Shaders in WebGL as of 2018?


I remember that we had to embed shaders into html like so:

<script id="fragmentShader" type="x-shader/x-vertex"> </script>
<script id="vertexShader" type="x-shader/x-vertex"></script>

For me this isnt ideal. Of course I could create shader files and use PHP to include them but I dont want that either.

Is there any alternatives to use shaders in HTML without third party tools?


Solution

  • The shader code has to be available somehow to the WebGL code, so there is no magic here. Some alternatives are:

    • Use Ajax to retrieve the shader's source code. In this case, your HTML would be free of shaders and the Javascript code would retrieve them by making asynchronous calls. The disadvantage of this approach is that you may have lots of requests and the page loading time may be affected.
    • Hardcode the shader's source in the Javascript code as string literals. This would be hard to maintain since you would be mixing Javascript code with shader code in the same files. It may work for small projects, but it will bring headaches in the long run.
    • Use WebAssembly and compile your code (including shader sources) to a wasm file. In this case the shader sources will be hidden inside the wasm file and will be processed directly by the browser.
    • Use a toolkit to create a distribution bundle. You can keep your shaders and Javascript code separate and organized (e.g., into directories, etc.). Then you can use a Javascript toolkit like Gulp or Grunt to process the code and merge them into one single source file. You can look at the source code of Three.js and see how it is organized. If you want to use that library, all you have to do is import one single file into your HTML page. That file contains the Javascript and related shaders.