The THREE.TextureLoader() function will repeatedly load a single texture, potentially more than 20 times

An issue has been discovered with the THREE.TextureLoader() function, as it seems to load the same assets multiple times (often 20 times or more) in an unexpected and erroneous manner.

The screenshot below from the browser console illustrates this behavior:

https://i.sstatic.net/Bdhg9.jpg

See the code snippet below that is used to load and apply textures:

Element.prototype.createShaderMaterial = function (uniforms, vertexShader, fragmentShader) {
    var loader = new THREE.TextureLoader();
    uniforms.texture.value = loader.load(this.texture);

    return new THREE.ShaderMaterial({
        uniforms: uniforms,
        vertexShader: vertexShader,
        fragmentShader: fragmentShader,
        wireframe: true
    });
};

A live preview of the issue can be found at: and the game's code is available here: https://github.com/alexprut/earth-defender/tree/master/client/js

What could be causing this behavior? Why is the same image being loaded multiple times?

Answer №1

It is a known fact that the THREE.TextureLoader() function does not cache textures by default. This can lead to multiple HTTP requests being made for the same texture if used repeatedly in different objects.

Fortunately, a solution to this caching issue can be implemented using a simple cache module following the Singleton or Module pattern:

var TextureLoader = (function () {
    var _instance = null;

    var Loader = function () {
        var _loader = new THREE.TextureLoader();
        var _cache = [];

        function _cachePush(elem, val) {
            _cache.push({
                element: elem,
                value: val
            });
        }

        function _cacheSearch(elem) {
            for (var i = 0; i < _cache.length; i++) {
                if (_cache[i].element === elem) {
                    return _cache[i].value;
                }
            }

            return false;
        }

        function load(texture) {
            var match = _cacheSearch(texture);

            if (match) {
                return match;
            }

            var val = _loader.load(texture);
            _cachePush(texture, val);

            return val;
        }

        return {
            load: load
        }
    };

    function getInstance() {
        return (_instance) ? _instance : _instance = Loader();
    }

    return {
        getInstance: getInstance
    }
})();

To efficiently use and cache textures, simply call the following function:

TextureLoader.getInstance().load(texture);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhance your networking capabilities with a Node.js HTTP proxy featuring a dynamic proxy

I'm attempting to make websockets function properly with node-http-proxy. The unique aspect is that I am using a proxy table configuration: var options = { router: { 'a.websterten.com': '127.0.0.1:150', 'b.websterten. ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...

Ways to retrieve lost methods in django-endless-pagination?

When new containers are added with ajax, the methods initialized for them stop working. How can I ensure that django-endless-pagination adds some JQuery to its generated containers? For instance: $(".fact").each(function() { $(this).css('border- ...

Add a CSS file to the browser-sync with proxy functionality

Currently, I have a script that I utilize to proxy a live website in order to make CSS modifications. Instead of replacing the online CSS file with a local one using a rewrite, I am exploring the possibility of injecting an entirely new file below the exis ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

Checking dates in a JavaScript form

var myForm = document.getElementById("form"); document.bgColor="#FFFFCC"; //page styling myForm.style.color="blue"; myForm.style.fontSize="20px"; myForm.style.fontWeight="400"; myForm.style.fontFamily="arial"; function validateForm() { var firstname = d ...

Twilio's phone calls are programmed to end after just 2 minutes

For the past week, I've been dealing with a frustrating issue where calls are being automatically disconnected after 2 minutes of recording. Here is the TwiML code: <Response> <Say voice="woman" language="en">Hii Welcome to our App</Sa ...

Unregistering an event with AngularJS

Exploring the functions of a controller named MyCtrl: class MyCtrl { constructor($scope, $rootScope, ...) { this.$scope = $scope; this.$rootScope = $rootScope; this.doThis = _debounce(this.resize.bind(this), 300); ... ...

Utilizing query parameters in JavaScript

When querying data from the database using passed parameters, I encountered an issue. For example: http://localhost:3030/people?$skip=0&$limit=25&$sort[name]=0&description[$name]=rajiv I wanted to add an extra parameter without including it in ...

`Incorporating dynamic link filtering in vis.js`

Can links and nodes be filtered in a vis.js network? I have configured a DataSet for both nodes and edges as follows: function drawNetwork(container){ var nodes = new vis.DataSet(); populateNodes(nodes); // implementation details skipped ...

Vite terminal not executing Npm commands

Here is what I entered: npm run dev Error: npm ERR! Missing script: "dev" npm ERR! npm ERR! To see a list of scripts, run: npm ERR! npm run npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\andre\AppData&bs ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

React: Introducing the latest router feature post-login

I'm facing an issue with the Router in React. After a successful login, I am changing the type state in Redux from 0 to 1. However, when I try to make a switch in my App file, I encounter an error. Warning: [react-router] You cannot change <Router ...

Can you clarify the functionality of this loop? I am having trouble grasping how it produces the final result

Seeking clarification on the highlighted section] https://i.sstatic.net/dyrKS.png I need assistance in understanding how the use of "text" helps to print the following literal. ...

Customizing the color of cells in an HTML table within a JSON based on their status

Would you like to learn how to customize the color of cells in an HTML table based on the status of a college semester's course map? The table represents all the necessary courses for your major, with green indicating completed courses, yellow for cou ...

Importing events from the calendar causes disarray in other data columns when sorted by date

I have a unique code that successfully imports my shared Google Calendar into a spreadsheet. In my medical office, I manage all appointments through a master Calendar. The calendar data includes start time, location, description, and title in columns B, ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

How can I display a PHP variable in JavaScript?

I am having trouble displaying a PHP variable in Javascript; Below is the code I am using: <script type="text/javascript> $(document).ready(function (){ var n=<?php echo json_encode($count)?>; for(var i=0;i<n;i++){ var div ...

What is the optimal location for making API requests in a React/Redux/Reach Router application?

I'm struggling to figure out the optimal location for making API calls in my app. My main component structure looks like this: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> ...