Pause until the existence of document.body is confirmed

Recently, I developed a Chrome extension that runs before the page fully loads by setting the attribute "run_at": "document_start". One issue I encountered is that I need to insert a div tag into the body of the webpage as soon as it is created. However, at that point, document.body is null so I can't append any tags to it.

I am not concerned with waiting for the full loading of the body, I just need it to exist.

I am currently exploring ways to be notified when the body tag in HTML is created (not necessarily fully loaded, just created). Are there any event handlers available for this specific scenario that I could implement?

In addition, I would prefer not to rely on jQuery or any other third-party library and instead utilize built-in functions.

Answer №1

If you want to track changes in the DOM structure, you can utilize a mutation observer on the document.documentElement element. This way, you can monitor for any additions to its child elements, particularly checking if a new body element is created.

Check out this sample: Live Example

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
  <script>
    (function() {
      "use strict";

      var observer = new MutationObserver(function() {
        if (document.body) {
          // Body element now exists
          document.body.insertAdjacentHTML(
            "beforeend",
            "<div>Found <code>body</code></div>"
          );
          observer.disconnect();
        }
      });
      observer.observe(document.documentElement, {childList: true});
    })();
  </script>
</head>
<body>
  <div id="foo"></div>
</body>
</html>

Answer №2

If you need to wait for the entire document to load, you can utilize the DOMContentLoaded event which functions similarly to $(document).ready()

document.addEventListener("DOMContentLoaded", function(event) {
   console.log("DOM fully loaded and parsed");
});

According to MDN, the DOMContentLoaded event is triggered when the browser has finished parsing the document entirely, even before stylesheets, images, and subframes have completed loading (the load event can be used for detecting a fully-loaded page).

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

The Java.lang.finalize heap became too large during the Hadoop URL parsing task

I'm currently working on analyzing the content of various homepage URLs by utilizing a Hadoop mapper without a reducer. This mapper fetches the URLs and sends them to a parser class for further analysis. The parser leverages Jericho's html parse ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

An issue has arisen with NextJS Link where it is failing to populate an anchor tag

In my React + NextJS project, I am struggling to display a list of products similar to what you would find on an ecommerce category page. Each product is wrapped in a p tag and should link to its corresponding detail page using an anchor a tag. Although t ...

Difficulty encountered when trying to obtain div height automatically

For a while now, I've been attempting to dynamically determine the height of an image as the browser window is adjusted. Despite using console.log() to verify my results, I keep getting a value of 0. What could be causing this discrepancy? $(functio ...

How to dynamically add events to a JQuery FullCalendar using a loop

When utilizing the jQuery full calendar, I need to dynamically set events based on data obtained from a database. To achieve this, I am using data attributes to assign values and then display them on the calendar. Below is an example of my html twig code: ...

If the value of the "Global Region" field in the PDF form is not empty, then execute the following JavaScript code:

I need to restrict access to a PDF form when the "Global Region" field is filled out. Testing this code can be time-consuming, so I want to confirm that the syntax to check for a NOT NULL value in the Global Region Field is correct. if(this.getField("Gl ...

``Text Aligns Perfectly in the Middle Horizontally, yet Shifts Slightly Off-C

Two rectangular divs were created, each measuring 60px wide and 150px tall with text inside. The goal was to align the text vertically within the rectangles, achieved by using transform: rotate(-90deg). The challenge arose when trying to center the vertic ...

Mobile devices offer a seamless vertical scrolling experience

Here is the HTML structure I am working with: <div> <a>..</a> <i>..</i> <a>..</a> <i>..</i> <a>..</a> <i>..</i> </div> On larger screens, all elements are dis ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

"Switching from vertical to horizontal time line in @devexpress/dx-react-scheduler-material-ui: A step-by-step guide

Is there a way to switch the Time to a horizontal line using @devexpress/dx-react-scheduler-material-ui? <WeekView startDayHour={7} endDayHour={20} timeTableCellComponent={TimeTableCell} dayScaleCellComponent={DayScaleCell} /> Click ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

Applying CSS borders with circular corners

Can this unique border style be achieved using only CSS? ...

Guide to setting up Date Range Validator within MVC 4

Is there a way to limit the user from inputting a date outside of a specific range in my MVC 4 application? I'd appreciate any advice on how to achieve this. ...

What are the steps to determine if a radio has been examined through programming?

In my form page, users can input an ID to fetch profile data from a MySQL database using AJAX. The retrieved data is then displayed in the form for editing. One part of the form consists of radio buttons to select a year level (e.g., "1", "2", "3", etc). ...

What is the best way to exclude certain values from Objects in Javascript?

Imagine having an object structured like this: "errors": { "name": { "name": "ValidatorError", "message": "Minimum length 6 characters.", "propert ...

Issue with border radius in MUI 5 affecting table body and footer elements

Currently, I am diving into a new project utilizing React version 18.2 and MUI 5.10.3 library. My main task involves designing a table with specific styles within one of the components. The table header should not display any border lines. The table body ...

Operating on a duplicate of the array is necessary for mapping an array of objects to function properly

I'm starting to uncover a mysterious aspect of Javascript that has eluded me thus far. Recently, I've been pulling an array of objects from a database using Sequelize. This array is quite intricate, with several associations included. Here' ...

Creating a button in ReactJS with text displayed under an icon

Presently, I am working with a component that looks like this: https://i.stack.imgur.com/qGCwj.png This is the code for the component: import React from "react"; import {withStyles} from "material-ui/styles"; import Settings from "material-ui-icons/Setti ...

Functionality of multiple sliders

Is there a more efficient way to handle the fading in and out of sections on a slider? I currently have separate functions for each section, but I'd like to simplify it so that I only need one function for all 100 sections. Any suggestions? $(&apos ...