Issue with my lazyloading extension for Mootools

Seeking to create a plugin for sequential image downloads using MooTools. Assuming there are images with the img tag inside a div with the class imageswrapper. The goal is to download each image in order, one after the other until all images are loaded.

window.addEvent('domready', function(){
// retrieve all images within the div with the class 'imageswrapper'
var imagesArray = $$('.imageswrapper img');
var tempProperty = '';
// hide the images and assign the 'data-src' attribute to prevent background downloading
for (var i=0; i<imagesArray.length; i++) {
    tempProperty = imagesArray[i].getProperty('src');
    imagesArray[i].removeProperty('src');
    imagesArray[i].setProperty('data-src', tempProperty);
}

tempProperty = '';
var iterator = 0;

// select the container where pictures will be inserted
var injDiv = $$('div.imageswrapper');

// recursive function that triggers when a new image is loaded
function imgBomber() {
    // base case for recursion
    if (iterator > (imagesArray.length-1)) {
        return false; 
    }
    tempProperty = imagesArray[iterator].getProperty('data-src');
    imagesArray[iterator].removeProperty('data-src');
    imagesArray[iterator].setProperty('src', tempProperty);
    imagesArray[iterator].addEvent('load', function() {
        imagesArray[iterator].inject(injDiv);
        iterator++;
        imgBomber();
    });

} ;
imgBomber();
});

Answer №1

Upon reviewing the code, there are several issues that stand out. The main issue seems to be unidentified, so I will provide some feedback and suggestions until the specific problems are identified and shared (or provided through a jsfiddle).

  • Running the code in domready may lead to images being downloaded based on the src property before you initiate data loading. Consider sending data-src directly from the server beforehand.

  • The major problem lies in:

    var injDiv = $$('div.imageswrapper');
    returning a collection instead of a single element, making it incompatible with inject. Use
    var injDiv = document.getElement('div.imageswrapper');
    instead.

  • Issues arise with the load events and cross-browser compatibility for .addEvent('load'). It's essential to clean up after executing these events, especially in IE < 9 where load triggers unnecessarily. Additionally, lacking onerror and onabort handlers can halt the loader on unexpected responses like 404 errors.

  • Avoid using data-src for storing data as it can be slow. Utilize MooTools Element storage methods such as el.store('src', oldSource), el.retrieve('src'), and el.eliminate('src') for faster operations.

  • Be cautious about exposing iterators to outer scopes to prevent potential issues.

  • Utilize MooTools API functions like .set() and .get() over .getProperty() and .setProperty().

  • Avoid using for (var i) iterators for asynchronous operations to ensure correct index referencing. Instead, consider using MooTools' .each(fn(item, index), scope) method from Elements / Array.

It appears your problem has been addressed on multiple levels by solutions such as my pre-loader plugin which offers framework-agnostic image loading features with options for parallel or pipelined downloads along with progress events. You can view an example at http://jsfiddle.net/dimitar/mFQm6/ to see the functionalities described.

MooTools also provides solutions like Asset.js - for handling assets including images. Take inspiration from their implementation available at https://github.com/mootools/mootools-more/blob/master/Source/Utilities/Assets.js.

For a demonstration leveraging my pre-loader class, check out this example: http://jsfiddle.net/dimitar/JhpsH/

(function(){
    var imagesToLoad = [],
        imgDiv = document.getElement('div.injecthere');

    $$('.imageswrapper img').each(function(el){
        imagesToLoad.push(el.get('src'));
        el.erase('src');
    });

    new preLoader(imagesToLoad, {
        pipeline: true,
        onProgress: function(img, imageEl, index){
            imgDiv.adopt(imageEl);
        }
    });

}());

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

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

What is the best way to retrieve an ID when parsing JSON recursively?

Could you provide guidance on how to retrieve the IDs of all children when parsing JSON data? I have attempted to use a recursive function, but it seems to be calling infinitely. For reference, here is my code snippet: http://jsfiddle.net/Ds8vQ/ for(var ...

Is the process.env.NODE_ENV automatically set to 'production'?

While examining someone else's code, I noticed this particular line. if (process.env.NODE_ENV === 'production') { ... The application in question is a node.js app with express server and reactjs front-end. If we were to deploy it on Heroku ...

implementing dynamic navigation bar, when transforming into a dropdown menu using ReactJS

I am currently utilizing a navigation bar from a Bootstrap theme within my React project. The navigation bar includes an in-built media query that determines whether it should display as a dropdown menu or not, with a toggler to handle the dropdown functi ...

Formik: encountering target as undefined while passing Material UI Date Picker as prop to React Component

I'm currently working on developing a component that can be reused. The idea is to pass form fields as props, but I ran into an issue when clicking on the datepicker field. The error message that pops up is: TypeError: target is undefined Any sugge ...

Switch between different table rows

I have here a table that is used for displaying menu and submenu items. It's a mix of PHP (to fetch the menu items and their respective submenus) and HTML. What I am trying to figure out is how to toggle the visibility of only the submenu items under ...

Encourage (or kindly request) the user to refresh the browser

I manage a website that heavily relies on javascript and ajax functionality. I have found ways to make users refresh their browsers upon initial loading, but what about after they have already been using the site? I am looking to improve the speed of the ...

JavaScript code that moves the active link to the top of the navigation when the window width is less than or equal to 800px

I'm working on a responsive navigation that is fixed at the top and switches from horizontal to vertical when the screen size is less than or equal to 800 pixels wide. However, I'm facing an issue with moving the active link to the top of the na ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

When using $dialogs.create on my website, a popup form appears with specific formatting limitations dictated by the defining code

When a user clicks a button on my website, a function in the controller is triggered. Here is the function that runs when the button is pressed: $scope.launch = function(idOfSpotOfInterest, schedOfSpotOfInterest){ var dlg = null; dlg = $dialogs. ...

Choose the option in real-time with Jquery

I'm currently developing a dynamic HTML for Select Option as seen below: item += "<td class='ddl' style='width:40%;'>"; item += "<select>" item += " <option id='list' name='selector' value=" + se ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

The inclusion of HttpClient is causing issues with the functionality of my component

Currently, I am facing an issue with my Angular service called ConnexionService. The problem arises when I try to incorporate CSV files into this service using HttpClient. Strangely, the component associated with this service fails to display once HttpClie ...

Here are some tips for retrieving information from a JavaScript object

My goal is to extract the values of free_time, done_ratio, criticalTask, and dependency from a JavaScript object for each task. I attempted to achieve this, but unfortunately, it didn't yield the desired results. var mock_data_allocation = {"alloc ...

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

Populating Dropdown list with values based on input provided in Textbox

Can you assist me in finding the solution to this issue? I have a TextBox and a DropDown list. For example, if I type "Anu" into the textbox, I want it to populate the dropdown list based on the text entered. How can I achieve this? I am working with vb. ...

Setting the font-size in HTML/CSS to dynamically adjust and fill the entire width and height of its

I'm trying to make a <div> element adjust its size based on the browser window. Within this <div>, there is a paragraph of text: <div style="width:80%; height:80%; margin:10%;"> <p>Paragraph of text. Paragraph of text. Pa ...