What is causing my JavaScript to function properly without the need for the 'defer' keyword?

After crafting the subsequent HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="j1.js" **defer**></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elderflower</title>
</head>
<body>
    <h1 class="target">Hii</h1>
    <h1>Unchanged</h1>
    <h1 class="target">Hii</h1>
</body>
</html>

and here's the javascript snippet provided:

let el = document.querySelectorAll(".target");
for(let i=0;i<el.length;i++)
{
    el[i].innerText = "Altered by JS";
}

Why is it that my javascript fails to yield any changes until I insert the term "defer" on line 4 within the HTML?

Answer №1

Make sure to place the script tag at the end of your file to ensure it gets executed after the body has been parsed.

If you need more information, check out this detailed explanation on the optimal placement of <script> tags in HTML markup.

Answer №2

The reason for this is that the script is being loaded before your HTML, resulting in an empty DOM.

By using defer, the script will load after your HTML, similar to placing your script tag at the bottom of the file. This helps with handling asynchronous tasks when loading multiple JavaScript files, making the process more efficient.

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

Editing in real time, yet no instance to be found

I have developed my own custom non-jQuery ajax solution for building web applications. Recently, I encountered compatibility issues with IE9 while using TinyMCE, so I am considering switching to CKeditor. The editable content is contained within a div str ...

Creating multiple countdowns in AngularJS using ng-repeat is a handy feature to have

Currently, I have a small AngularJS application that is designed to search for users and display their upcoming meetings. The data is retrieved from the server in JSON format, with time displayed in UTC for easier calculation to local times. While I have s ...

Issue with adding a key:value pair to res.locals.object in Node/Express not functioning as expected

Currently, I am working on constructing an object within res.locals by executing multiple MongoDB operations and utilizing the next() middleware. Once I have added an object to res.locals, such as: res.locals.newObject, my goal is to subsequently add addi ...

Node.js delete operator not performing as anticipated

Within my node.js express application, I am fetching a user object from the database: const newUser = await User.create({ username, password, email, avatar, }) However, before sending back the response containing the user object, I ...

Receiving Output from an AJAX Request

My PHP script is set up to verify the validity of an email address, returning either true or false. I've been attempting to use AJAX to call this PHP file and pass the result back to a Javascript function, but unfortunately, I haven't been succes ...

Tips on configuring HTTP headers for numerous messages within Node-RED?

I've been working on a flow that involves breaking down a large message into smaller messages. I've successfully implemented the logic for splitting the message, but when attempting to send these small messages to an http response node, I encount ...

Step-by-step guide on performing a GET request to the api.github using an Express server

I've been stuck for the past 3 days and have done extensive research on the internet. Here's the code snippet I'm struggling with: api.js const express = require('express'); const router = express.Router(); var http = require(&apo ...

Could this be a substance made of pure white energy?

It appears that the default color for SpriteMaterial is 0xFFFFFF, which indicates no color. However, if I change the color property of the material to say 0xFF0000, the sprite will display a red tint. If I desire a white tint instead, how can this be achi ...

What is the best way to retrieve the data from this date object?

How can I access the date and time in the code below? I've attempted using functions within the Text block without success. It's unclear to me what mistake I'm making or how to correctly access this object, or transform it into an object th ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

Unable to modify information retrieved from API. Error: Unable to assign to property that is set to read-only

Using an API call, I retrieve some data. getPosts(postRequest: PostRequest): void { this._postService.getPosts(postRequest).subscribe(result => { const postList = result as PostList this.posts = postList.posts }); ...

What could be causing the first bar in Chart.js to appear smaller or not show up at all?

Hey there, I'm currently working on displaying some bar charts using Charts js. However, I've run into an issue with the first column not showing up correctly. Here is my code snippet: var options = { scales: { yAxes: [{ display: tru ...

Iterating through images one time and capturing the mouse coordinates for every click made by the user

I have the following code snippet that displays a series of images and I would like to capture the coordinates of each mouse click on these images. Is there a way to send these coordinates to my email at the end of the image loop? Any assistance in achievi ...

How come .trim() isn't cooperating with me?

I am encountering an issue with this particular piece of javascript. Every time I attempt to use it, nothing is displayed in my div. Instead, it simply adds ?weight=NumberInputed&measure=lbsOrkgs&submit=Submit to the URL. <h2>What size d ...

Is there a way to show the text within a div tag in a tooltip without relying on jQuery?

Is there a way to display the text content of an HTML element inside a tooltip? I am struggling to achieve this, as I would like to have the word test appear in the tooltip, but it's not working. Unfortunately, we are not using jQuery in our code bas ...

Navigating through tabs on a mobile device by scrolling sideways

Is there a way to create a dropdown menu with tabs in a bootstrap site where the icons extend beyond the width of the menu, allowing mobile users to swipe horizontally? Check out the code here: https://jsfiddle.net/6yw6rp02/1/ This is the current code s ...

Anticipating the information that I will retrieve from the server

Greetings to all! I am still new here, so please bear with me if my layout is not up to par. I have a reactive form where I submit data to the server (mongodb database). After that, I aim to redirect to a new path while passing along the ID element provid ...

A coding algorithm for determining text similarity percentage by calculating the edit distance

I have a good understanding of various edit-distance algorithms in JavaScript, but my goal is to calculate text similarity as a percentage based on them. Can anyone provide guidance on how to implement this feature? ...

Implementing a Jquery Switcher: A Step-by-Step Guide

I always strive to provide clear and specific details about my question. My goal is to create an Alert Box for different types of inputs, where all inputs will trigger the same alert message in the box instead of separate alerts. I attempted to implement ...

How can Angular be used to fetch the name associated with a user_id in Laravel?

There seems to be a problem with fetching the name attribute along with the title and body attributes. The name appears empty on page refresh but shows up automatically upon submission. Interestingly, angularjs is unable to retrieve the name successfully. ...