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.
Header Image
TypeScript Binary Heap

Yesterday I converted a Binary Heap data structure in TypeScript. The original code is here, in the Eloquent JavaScript online book by Marijn Haverbeke. In short, a Binary Heap is a common …

Header Image
Quick Dev Tips: Pixel-Perfect Scaling of a Phaser game

As you may know, I am in the middle of developing a demo for some Smart Pathfinding, and I’m using Phaser and TypeScript for it. Unfortunately, as soon as I started coding a couple of …

Header Image
Javascript is not so bad, after all

I have to admit it. I was a big Javascript hater. I used to criticize the language on every possible aspect: syntax, maintainability, error prevention and management, and so on. Let me be …

comments powered by Disqus