Search code examples
javascriptglslwebglshader

load GLSL file (WebGL) in HTML?


What I want:

<script src="shader.glsl" type="x-shader/x-fragment"></script>
<script src="shader.glsl" type="x-shader/x-vertex"></script>

or:

<script src="shader.frag" type="x-shader/x-fragment"></script>
<script src="shader.vert" type="x-shader/x-vertex"></script>

So I have 2 simple shader types:

  • type=x-shader/x-fragment

    precision mediump float;
    
    void main(void) {
        gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
    }
    
  • type=x-shader/x-vertex

    attribute vec3 aVertexPosition;
    
    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;
    
    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
    }
    

The shaders come from this WebGL tutorial


  1. Can I add these 2 types in one .glsl?
  2. If not are their other file formats for the shader types like:

    • .vert
    • .frag

Q: For what do I want to use this?
A: Dynamically loading my files from JavaScript and insert it to my HTML file.

Q: Do you want to know how to load dynamically files?
A: No that is irrelevant to the question "load GLSL file (WebGL) in HTML?"

Q: What do you want then?
A: Look at the What I want at the start of the question.

Q: Do you want to share your JavaScript import code?
A: Yes but I think that is irrelevant information to be able to answer the question


Solution

  • It is not possible this way.
    See specs: https://www.w3.org/TR/html5/semantics-scripting.html#data-block

    When used to include data blocks, the data must be embedded inline, the format of the data must be given using the type attribute, and the contents of the script element must conform to the requirements defined for the format used. The src, charset, async, defer, crossorigin, and nonce attributes must not be specified.

    (So data blocks have to be inline, as shown in https://www.w3.org/TR/html5/semantics-scripting.html#dom-htmlscriptelement-text - then they can be accessed via .text or .textContent)

    So revert to XMLHttpRequest (or some AJAX wrapper for it) if you want to load GLSL from separate files.