Determine if the content has finished loading once it has been added using JavaScript

I am currently working on a project in pure JavaScript that involves implementing a feature similar to Facebook's message loading. This means that when you scroll to the end of the page, new HTML content is loaded and added to the page. The additional content is retrieved through Ajax. However, adding this HTML may require the page to load extra images. Is there a method I can use to determine when the page has finished loading all elements, including the new images?

Answer №1

To ensure that appended elements trigger the load event, you can attach the event to those elements using the following code:

function LOADER_FUNCTION(e) {
   console.log("LOADED", e.target);
}

var element = document.querySelector('#parent');
for(i=0; i<element.childNodes.length; i++) {
   element.childNodes[i].addEventListener('load', LOADER_FUNCTION);
}

The LOADER_FUNCTION will be called when the content within the element is ready. It's interesting to note that this method does not work when attached to the parent element.

Here is a demonstration of how this works without Ajax but with similar conditions. By utilizing innerHTML instead of createElement -> appendChild, I am able to show that this event is not restricted to specific methods:

(function(){
  var element = document.getElementById('parent');

  function LOADER_FUNCTION(e) {
     document.querySelector('.status').innerText = ("LOADED " + e.target.tagName);
     console.log("LOADED", e.target);
  }
  
  element.innerHTML = "<img src='http://i.imgur.com/OfSN9oH.jpg'>";

  for(i=0; i<element.childNodes.length; i++){
    element.childNodes[i].addEventListener('load', LOADER_FUNCTION);
  }
})()
<div class='status'></div>
<div id="parent"></div>

For dealing with nested children in append or innerHTML operations, use element.querySelectorAll('*').

https://jsfiddle.net/bckpL9k6/1/

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

Retrieving and submitting text in a NodeJS environment

I'm attempting to retrieve text from an API that only provides a string of text ((here)), but I am encountering difficulties in displaying it accurately. When I try to post it, the output shows as [object Response], and the console.log is not showing ...

Having trouble with React Axios GET request? Error message: "name.toUpperCase is not a function."

I am currently facing an issue with a basic React app I have created. Whenever I try to make a simple GET request, a TypeError occurs saying 'name.toUppercase is not a function'. There is only one function in my code. Can anyone provide insights ...

Issue: Configuration Error - CKEditor5 cannot be loaded for extension in Vuejs

Hey everyone, I'm currently facing an issue. I'm trying to customize a build and everything works fine in the cloned ckeditor along with the sample.html file. However, when attempting to implement the customized build in Vue 2, I encounter an err ...

What is the best way to resize a PDF to match the width and height of a canvas using

I need help with a project involving rendering previews of PDF documents in a UI similar to Google Docs. {documents.map((doc) => { return ( <div key={doc.id} className=" ...

Removing a value from a JSON object by utilizing the .map function

My JSON object is structured as follows: [{"box":1,"parent":[],"child":[{"boxId":2},{"boxId":3}]},{"box":2,"parent":[{"boxId":1}],"child":[]}] I am attempting to remove the element "child":[{"boxId":2} with boxId=2 from the object. I have tried using a , ...

Ways to activate ajax calls using a JavaScript chart

Newbie in the world of Javascript. I have a forced directed graph from spring.js and I am trying to trigger ajax from it when a user selects a node. However, I keep encountering an error: Uncaught SyntaxError: Unexpected token . The issue seems to be cente ...

Display the div element only when it is positioned in the center of the page

I am looking to create a smooth fade-in effect for a div when the user scrolls away from the top of the page, but I want the div to be hidden again as they approach the bottom of the page. Specifically, I would like the div to remain hidden when it is wit ...

Sending a JavaScript variable to the server-side code

My form consists of 2 inputs and a button. When a user enters a feed URL in the first input and clicks the button: <%= link_to "get name", { :controller => 'Feeds', :action => "get_title" }, :remote => true, :class=>'btn btn ...

Is it possible to integrate a comprehensive full text search capability on a static website directly on the client side, without reliance on a database

There is a script that I came across, possibly in npm's source code, but I didn't write it myself. I'm intrigued by the idea of refactoring this code to potentially enable a quick web crawl of a static site and generate a list of URLs leadin ...

Error encountered: Class not found exception in the context of JSONArray

import org.json.JSONArray; JSONArray json=new JSONArray(al); response.setContentType("application/json"); response.getWriter().print(json); } Despite having included the necessary jar in my project, I am encountering this error: SEVERE: Servle ...

Utilizing raycasting to target specific components within a glTF model and incorporate event listeners

I'm in the process of creating an interactive web application. Recently, I successfully imported a glb file into my scene. Now, I'm looking to incorporate two key functionalities: onMouseover: When hovering over one of the elements within the o ...

Setting up a specific print media query for the body element through JavaScript

I'm facing an issue with my web page that has a bootstrap modal which pops up when a button is clicked. I've added a print media query to print the content of the modal, but it's causing a problem. When I include the media query in the CSS, ...

Having trouble establishing a default route with React Router v5

I am facing an issue with setting the default route to the home page in react router v5. Despite trying several methods, I cannot get it to work as expected. Index.js import React from "react"; import ReactDOM from "react-dom"; import ...

The value of a Vuetify v-select input element does not remain stored within it

My Vuetify v-select component is set up like this: <v-select :name="search['type']" v-model="type" :items="typeOptions" label="Type" > </v-select> The typeOptions array looks like this: typeOptions: [ { text: ...

Is it possible for me to automatically send the user's email and username through code without requiring any information from them while using the tawk.to chat widget?

I need assistance with automatically sending the user's email and name when they open a chat window. I have tried various methods to pre-fill the form data but it still appears empty. Please let me know if there is something I am missing. Thank you ta ...

Launch target _blank within a modal instead of a new tab

I'm currently exploring ways to use vanilla JavaScript in order to display all external links - particularly those that typically open in a new tab or window - within a modal box instead. My goal is to implement a listener on external links (those no ...

CSS and JavaScript dropdown malfunctioning due to a position swap in internal CSS

This example demonstrates functionality .c1 { background-color:red; position:relative; } .c2 { background-color:blue; position:absolute; height:50px; width:100px; display:none;} .show { display:block; } <body> <button ...

Is this included in the total number of reads?

Following my query with CollectionsGroup, I attempted to retrieve the information of the parent's parent like this: db.collectionGroup('teams').where('players', 'array-contains', currentUser.uid).get().then(function(snaps ...

jQuery does not support the addition of new fields in HTML

Recently, I've been working on creating a lucky number generator. Initially, I developed it using C# and now I'm in the process of transitioning it to JavaScript and jQuery. You can view the latest version here. However, I've encountered an ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...