Loading GLTF model via XHR may take an infinite amount of time to reach full completion

I am attempting to load a GLTF model of a piano using XHR and showcase the loading progress on a webpage. The model is being loaded utilizing the Three.js library. On a local server, everything works perfectly - the loading percentage is shown accurately, and the model is rendered without any issues. However, upon hosting the code on a website, the loading percentage inexplicably displays as "Infinity%". An error message "Uncaught TypeError: Failed to set the 'value' property on 'HTMLProgressElement': The provided double value is non-finite" appears in the console. Despite my attempts to troubleshoot by modifying the code, I am unable to identify the root cause of this issue. I require assistance in comprehending why this is occurring and how it can be resolved.

Below is the code snippet (I've highlighted the problematic line with an arrow (after adding parseInt, it resulted in NaN%, rendering it ineffective)):

loader.load(
  "models/piano/piano.gltf",
  (gltf) => {
    piano = gltf.scene;
    scene.add(piano);
    piano.traverse((child) => {
      if (child.isMesh) {
        child.castShadow = true;
        child.receiveShadow = true;

        if (child.material.map) {
          child.material.map.anisotropy = 4;
        }
        if (child.material.roughness) {
          child.material.roughness = 0.2;
        }
        if (child.name.startsWith("key")) {
          child.userData = {
            position: child.position.y,
            rotation: child.rotation.x,
          };
          pianoKeys.push(child);
        }
      }
    });

    Promise.all(
      notes.map((note, index) => {
        loadingProgress.value = parseInt((index / 88) * 100);
        currentFile.innerHTML = `sounds/${note}.mp3<span>${
          index + 1
        } / 88</span>`;
        if (index + 1 == 88) {
          currentFile.innerHTML = `Finishing loading...`;
        }
        return new Promise((resolve) => {
          audioSources[note] = new Howl({
            src: [`sounds/${note}.mp3`],
            volume: 1,
            onload: resolve,
          });
        });
      })
    ).then(() => {
      filesLoaded();
    });
  },
  (xhr) => {
    const percentComplete = parseInt((xhr.loaded / xhr.total) * 100);
    currentFile.innerHTML = `models/piano/piano.gltf<span>${percentComplete}%</div>`; //  <--
    loadingProgress.value = percentComplete;
  }
);

Answer №1

One way to address this issue is as follows:

First, determine the file size of the model in bytes on your computer (for example, 289907). Next, store this value in a variable and utilize this variable for calculating the percentage loaded, instead of relying on xhr.total, since xhr.total may return 0.

Implementing this method has proven to be effective.

Answer №2

According to information found on this documentation page

During the loading process, the onProgress function is called. It takes the XMLHttpRequest instance as an argument, which includes .total and .loaded bytes. If the server doesn't specify the Content-Length header, .total will be 0.

It appears that the issue you're experiencing is due to the server not setting the correct header, resulting in: xhr.loaded / 0 = infinity

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

Experiencing code coverage challenges in Angular 8 relating to function properties

https://i.sstatic.net/WQpVB.png Looking for suggestions on how to create a unit test case in Jasmine to address the code coverage problem. Any ideas? ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...

Leveraging server-sent events to retrieve an array from a MySQL database using PHP

I've been attempting to implement server-sent events in order to fetch data from a database and dynamically update my HTML page whenever a new message is received. Here's the code I'm using: function update() { if(typeof(Event ...

A guide on implementing the href attribute in Material-ui

I previously asked about this code, but my wording was unclear. I am trying to get the menu items to work with href links. Currently, only the "Home" button works with href, while the "Sessions Home", "Book a Session", and "[S] Host a session" buttons do n ...

The process of generating collection names dynamically based on user information

My goal is to enhance the structure of my data collection and make it more organized. While I am familiar with accessing and retrieving data, I am unsure about creating the schema. Here is my current schema: var MySchema = new Schema ({ event: { ...

The MarkCompactCollector was unsuccessful in promoting the young object due to a failed allocation process

After successfully cloning a Git repository that houses a Vue project using the command git clone, I proceeded to run npm install in order to install all necessary dependencies, resulting in the creation of the node_modules folder. However, upon executing ...

Hidden button trigger is malfunctioning

I am attempting to activate a hidden button, but the event does not seem to be triggering. Here is the code snippet: <div class="dyn-inp-group"> <div class="dyn-inps"> <div class="form-group form-group-options col-xs-12 dyn-inp" ...

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: https://i.sstatic.net/lo8zM.png Mobile: https://i.sstatic.net/8xoW6. ...

How can I anchor a div Banner saying "Get 50% off our products" to the Navbar directly above it?

Bootstrap Question: How can I attach the div Banner ("50% off of our products") to the Navbar directly above it? The structure looks like this: <Navbar> </Navbar> <div> <span>Discount: 50% off of our products </span </di ...

Creating a standalone script using npm JS package for exporting

I'm currently utilizing the npm package manager in my latest project. Within my package.json file, I have a dependency specified: "dependencies": { "litepicker": "^2.0.11" }, The dependency is on litepicker, which i ...

React-native - Dropdownpicker - Error: Unable to retrieve label for selected choice

I'm encountering an issue with DropDownPicker in my react-native project during page load Here is the code snippet where I am using DropDownPicker: <DropDownPicker items={[ { la ...

It appears that the use of "window.location" is causing the ajax post

I'm facing an issue with sending data to PHP using AJAX and redirecting to the PHP file. It seems that when I redirect to the PHP file, the data sent through AJAX is not being received. My goal is to have a button click trigger the sending of data to ...

Whenever I change the value of a textbox using plain JavaScript, the text becomes hidden from view

I'm struggling to understand why this function is making the textbox value invisible. I attempted changing the hidden field to a visible field, but that didn't solve the issue. Would appreciate some guidance. Here's the complete page code, p ...

Wait for the definition of a variable before returning in React Native

I am currently receiving data asynchronously and displaying it within the render() function using {data}. My dilemma is how to ensure that the render() function waits until the variable is defined. Currently, the placeholder variable remains the same or d ...

Identify when a user switches tabs within the browser and when they switch applications away from the

I am interested in understanding the behavior of the tab's visibility state when a user switches tabs in a specific browser and when they switch out of the application entirely (switching away from the browser). var visibilityState, activeTab = ( ...

The integration of <form> with jQuery Ajax error

I have come across this HTML form function FormSubmit (){ $.ajax({ url:'dotar.php', type:'post', data:$('form').serialize(), success:function(){ setTi ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

JS receiving a reference to an undefined variable from Flask

I referenced this helpful post on Stack Overflow to transfer data from Flask to a JS file. Flask: @app.route('/') def home(): content = "Hello" return render_template('index.html', content=content) HTML <head> ...