Loading models asynchronously
In the Loading textures asynchronously recipe, we explained that Three.js offers helper functions to load different types of resources asynchronously. In this recipe, we'll look at how you can use the THREE.JSONLoader
object to load models asynchronously.
Getting ready
Before you get started with this recipe, make sure that you've walked through the steps explained in the Getting ready section of the Loading textures asynchronously recipe. In the following section, we'll reference the JavaScript callbacks defined in the Getting ready section of that recipe.
How to do it...
- Three.js also allows you to easily load external models. The following function shows you how to do this for the JSON models' Three.js uses. The same, however, applies to any of the other model loaders:
function loadModel(modelUrl) { var jsonLoader = new THREE.JSONLoader(); jsonLoader.load(modelUrl, onLoadCallback, null); }
- The
jsonLoader.load
function takes the following three arguments:- The first one is the location of the model you want to load
- The second is the callback to call when the model is successfully loaded
- The final parameter is the one that we can specify the path from where the texture images should be loaded
- When we call this function, you'll see the following output on the console:
There is more...
With this approach, the JSONLoader
object doesn't provide any feedback on how much it has loaded. If you want to load large models, it is nice to know something about the progress. The JSONLoader
object also provides an alternative way of loading models that also provides progress. In the Load model asynchronously with progress recipe, we show you how to load a model and provide feedback on the progress. Besides the THREE.JSONLoader
object, which loads Three.js' own proprietary models, Three.js is also shipped with a large number of loaders that you can use for other model formats. For an overview of what is provided by Three.js, please refer to https://github.com/mrdoob/three.js/tree/master/examples/js/loaders.