Mastodon Icon GitHub Icon LinkedIn Icon RSS Icon

THREE.js Shader Loading from External File

As usual, trying to nicely separate into different files the various application parts in JavaScript is a titanic challenge. This time, I wanted to separate the “.frag” and “.vert” shader programs into different files that I can load at runtime (instead of putting them into the HTML like a savage).

For some reason, there is no easy out-of-the-box way to do that. On the internet, there is a small library, but it depends on JQuery and I think it is insane to load JQuery on top of THREE.js just to load a couple of files. Therefore, I wrote a function to do that using the THREE.js integrated generic loader function.

This is just a convoluted asynchronous function to load the vertex and fragment shader file. Posting this here for future reference.

Update 5th October 2017

I realized that this article is more useful than I thought. At the same time, I dropped a snippet without any example on how to use it. It is time to fix this.

  1. First step. I published a complete example here. There are some more comments in the source code.
  2. You need to run the experiment in a web server (because of async file loading). Even a simple one like this or the built in Python one is more than enough.
  3. If you are working wit this, please, disable cache from your browser development tools. If you don’t do it refreshing the web page will not update the shaders. By disabling the cache you force your browser to always get the last version you just edited.
comments powered by Disqus