How to load external shader in javascript?

2019-08-13 22:53发布

问题:

I want to load the fragment shader from an external file, but it dont works. (after the shader is loaded, the alertbox don't appear.)

var fs = document.createElement('script');
fs.setAttribute("type","x-shader/x-fragment");
fs.setAttribute("src", "shader.fs");

fs.onload = function() {alert('done');}
document.getElementsByTagName("head")[0].appendChild(fs);

回答1:

Storing a shader in a script tag is simply a convention that several WebGL tutorials picked up to give the shader a simple place to "live". It doesn't have to be put in a script tag to work.

XHR is probably the easiest way to pull one down.

var shaderXhr = new XMLHttpRequest();
shaderXhr.open("GET", "shader.fs", true);
shaderXhr.onload = function() {
    yourShaderParsingRoutine(this.responseText);
};
shaderXhr.send(null);