The image loading and completion count function in JavaScript experiences sluggish performance on mobile devices

While this feature performs optimally on all the desktop browsers I've checked, it tends to have a glitch on mobile browsers. It often skips from 0% to 100% right away upon loading, or shows only a few numbers in between like 0%, 30%, 67%, 100%. Is there a way to make the image counting function run smoothly on mobile devices just like it does on desktop?

Answer №1

Even though there are areas for improvement in performance, it is important to note that the transition from 0% to 100% loading may appear faster on mobile than on a desktop due to various factors.

Web page images load in parallel, so multiple images finishing simultaneously can contribute to the quick progression from 0% to 100% completion. Additionally, desktop sites often serve larger image files compared to those served on mobile devices, resulting in longer loading times and more incremental progress on desktops.

It is essential to conduct testing across different desktops and mobile devices as internet speeds and hardware configurations vary, influencing loading times and overall performance results.


Regarding your code, here are some suggested modifications:

Your current script loops through all images once, offering only a snapshot of the loading progress at that moment. To provide accurate progress updates, consider setting up a load event handler for each image to track loaded counts dynamically. The .load event fires upon image completion without needing to test for .complete.

Furthermore, using querySelectorAll() instead of getElementsByTagName() can enhance performance by avoiding unnecessary re-scanning of the DOM for elements, especially if dealing with static images.

Lastly, optimize your code by utilizing .textContent when HTML parsing is not required, which reduces processing overhead.

// Create an array for image elements
var imgList = Array.prototype.slice.call(document.querySelectorAll("img"));
var numb = parent.document.getElementById("numb");
var imgListLength = imgList.length;
var start = 0;

// Iterate over image elements
imgList.forEach(function(img){
  // Add a load event listener for each image
  img.addEventListener("load", function(){
    // Update count and percentage
    numb.textContent = Math.round((++start / imgListLength) * 100);
  });
});

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

What is the best way to convert $('input[type=text]') into vanilla JavaScript?

How can I change this to plain JavaScript? I've been struggling to find a solution, any pointers? ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

Utilizing jQuery to Maintain State Across Page Refreshes with Cookies

Currently, I am attempting to create a script that can retain its state even after the page is refreshed. Here is my progress so far: Utilizing jQuery: $(window).ready(function() { var voteId = $('.gallery-item a'); $(voteId).click(function() ...

unable to retrieve the li element's ID when clicked

I am working on a code snippet to display tabs with dynamic content. $start = strtotime($_GET['date']); $dates = array(); for ($i = 0; $i <= 7; $i++) { $date = date('Y-m-d', strtotime("+$i day", $start)); $date1 = $ ...

Discovering the magic of obtaining a random element in Vue.js

I have 3 captivating hero images along with their unique content, and I am looking to showcase them randomly to users each time they refresh the page! My challenge lies in efficiently loading these large hero images using jQuery. Currently, all three imag ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

What could be causing the child view to not display the AJAX result?

An AJAX call is being made in the following manner: @Ajax.ActionLink("My Schedule", "GetSchedule", "Schedule", new { selectedDate = strToday}, new AjaxOptions { UpdateTargetId = "theTimes", InsertionMode = InsertionMode.Replace, HttpMethod = "GET" }) Th ...

Storing multiple items in an array using LocalForage

I have a challenge where I need to add multiple items to an array without overriding them. My initial approach was like this: localForage.getItem("data", (err, results) => { console.log('results', results) // var dataArray ...

Having trouble retrieving data through AJAX requests

My goal is to verify the existence of a user email on "blur()" using AJAX to send textbox data to PHP. Even though I can see the posted data in Firebug, I keep encountering an error: Undefined index: data. Despite numerous attempts, I have been unable to r ...

Troubleshooting the Confirm Form Resubmission problem on my website

Hello everyone! I'm working on a website and facing an issue where refreshing the page triggers a confirm form resubmission prompt. Could someone please advise me on how to resolve this? Thank you in advance! ...

Posting photos to MongoDB using Node.js and Express

I am currently facing an issue while attempting to upload an image using multer in Node.js. I have configured multer to save the uploaded images in the "upload" directory, and upon form submission, the image is successfully sent to the directory. However, ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Apollo Client's useQuery function is causing unnecessary refetches when using Next.js' router.push method

Currently, I'm facing an issue where a query within a useQuery Apollo Client hook is being re-run unnecessarily every time Next.js's router.push function is triggered. The problem code snippet looks like this: const Parent = () => { useQuery ...

Using `require` in place of `script` tags in a three.js file when working with Node.js environment

Instead of using the html script tag, I have implemented javascript require in my three.js file for node.js. Here is a snippet from an html file: <script src="../build/three.js"></script> <script src="js/controls/DragControls.js"></s ...

What is the best way to access the local Express server that is located in the same directory as the frontend project

This is the structure of my project - backend > node_modules > .env package-lock.json package.json server.js frontend > index.html style.css script.js server.js import dotenv from 'dotenv'; dotenv.config(); import express from &apo ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...

Utilizing Shopify API to seamlessly add items to cart without any redirection for a smoother shopping experience

Looking for a solution to submit an add to cart POST request without any redirection at all? I have tried changing return_to to "back" but that still reloads the page, which is not ideal. My goal is to smoothly add the item to the cart and notify the cli ...

Exploring the benefits of utilizing useState and localStorage in Next.js with server-side

Encountering an error consistently in the code snippet below: "localstorage is not defined" It seems like this issue arises because next.js attempts to render the page on the server. I made an attempt to place the const [advancedMode, setAdvanced ...