Could you please explain the distinctions among onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?

When it comes to editing my code, I rely on JSFiddle. However, I have noticed that in certain instances when running JavaScript or jQuery, the code only works if I choose "No wrap - <head>" or "No wrap - <body>".

CLICK HERE FOR THE JSFIDDLE EXAMPLE

If you check out the fiddle linked above, you'll see that clicking the <button> element won't trigger an alert() unless you have selected either "No wrap - <head>" or "No wrap - <body>".

I am naturally curious and always eager to understand how things function. Could someone explain what exactly this option changes and why it's necessary to make this change?

Answer №1

Executing on Page Load:

  • To ensure the code runs during the window's onLoad event, wrap it accordingly. This event triggers after the entire page, including images, has finished loading.

Executing on DOM Ready:

  • To execute the code when the DOM is ready, wrap it to be triggered by the onDomReady event. This event occurs once the DOM has been constructed and is accessible for manipulation.

No Wrap - Inside the <head>:

  • If you choose this option, your JavaScript code will be placed within the <head> section of the HTML document.

No Wrap - Inside the <body>:

  • Selecting this alternative places your JavaScript code within the <body> section of the HTML document.

Please take note that additional details are available in jsFiddle's documentation.

Answer №2

By using the onLoad and onDomready functions, your JavaScript code will run when the document has finished loading or when the DOM is ready. It's similar to writing your code like this:

Reference from Stackoverflow

<script type="text/javascript">
    //<![CDATA[
      window.onload=function(){ /* your js here */ }
   //]]>
</script>

If you choose the no wrap options, it means that you have added your script tag to either the head or body tags of the document in the way you are probably accustomed to doing.

<html>
 <head>
       <title>Stuff</title>
 <script>
   /* your code */
 </script>
 </head>

Answer №3

When onload is triggered, it indicates that all resources on the page have been fully loaded, including images, CSS, and JavaScript. On the other hand, domReady simply means that the DOM tree has finished constructing.

Answer №4

When all content has finished loading, the load event serves as a general signal for completion. Various elements are able to support this, such as external SCRIPT and IMG, IFRAME which trigger the event upon completing the download of their content.

In contrast, the DOMContentLoaded event is triggered on the document when the page is fully prepared. It patiently waits for both the full HTML markup and any necessary scripts to be loaded before firing. This event is supported by all browsers except for IE versions below 9.

Answer №5

Learn more details regarding the onDomready function.

The code snippet below demonstrates how JSFiddle wraps and executes our code, providing support for browsers lacking the addEventListener method to handle the DOMContentLoaded event.

<script type="text/javascript">
//<![CDATA[
    var VanillaExecuteOnDomReady = function() {
        // Insert your JavaScript code here.
    }

    var hasRunFlag = 0;

    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", function(){
            hasRunFlag = 1; 
            VanillaExecuteOnDomReady();
        }, false);
    } else if (document.all && !window.opera) {
        document.write('<script type="text/javascript" id="loadcontenttag" defer="defer" src="javascript:void(0)"><\/script>');
        var loadcontenttag = document.getElementById("loadcontenttag")
        loadcontenttag.onreadystatechange=function(){
            if (this.readyState=="complete"){
                hasRunFlag=1;
                VanillaExecuteOnDomReady();
            }
        }
    }

    window.onload = function(){
      setTimeout("if (!hasRunFlag){VanillaExecuteOnDomReady}", 0);
    }
//]]>
</script>

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

Does the notion of "Execution context and the stack" only pertain to web browsers?

Does the concept of "Execution context and the stack" only apply to browsers, or is it also utilized in other environments such as NodeJS? I've crafted 2 statements but unsure if they are accurate: 1- "The environment for JavaScript is not solely the ...

When the collapse button is clicked, I aim to increase the top value by 100. Subsequently, upon a second click, the top value should

https://i.stack.imgur.com/p9owU.jpghttps://i.stack.imgur.com/Kwtnh.jpg I attempted to utilize jQuery toggle, but unfortunately, it is not functioning as expected. <script> $(document).ready(function () { $(".sidebar ul li&quo ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

Comparing the size of a MongoDB array to another field in a document: how can it be done?

Need guidance on querying MongoDB for documents that have a specific number of users in them. This needs to be done through both the mongo console and JavaScript in Node.js: db.turnys.find( { users:{$size:seats } } ) The structure of turnydb.turnys colle ...

Attempting to incorporate Google charts into a div using jQuery's load function

Trying to incorporate a basic Google chart using jQuery .load functionality to transfer the chart into another webpage with a specific containing DIV: <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi">< ...

Steps for displaying only one collapse at a time using either Bootstrap 3 or Bootstrap 4

As I work on constructing a website from the ground up using Bootstrap 4, I have encountered a roadblock that may be simple for an experienced Bootstrap developer. While I was able to find a solution involving raw Javascript code to collapse one element at ...

Discover the location by determining the distance from established points

Before I get redirected to this particular question, let me clarify that while I've come across it, I am unable to comprehend its content (I wish I could). What I'm really seeking is a straightforward method (bearing in mind my limited math skill ...

jquery dialog box displaying a webpage

I am looking to implement a feature where, upon clicking the edit link in the last column of my dataTable, a separate page for editing should open within a jQuery dialog box. The goal is to seamlessly submit data while providing a user-friendly experienc ...

What causes a syntax error when attempting to install Babel?

Can someone explain why babel installations are failing with the error shown below? https://i.sstatic.net/pSuDe.png The logs related to this issue can be found here, https://i.sstatic.net/l8xld.png ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

Troubleshooting CSS Hover Not Displaying Properly in Angular 14

In the footer class of my HTML, there is a code snippet with chevrons: <div class="link-list"> <div *ngFor="let link of insideLinksLeft | originalOrderKeyValue" class="link"> <a [href]="link.val ...

Retrieve documents from MongoDB database that have specific characteristics

Hello everyone, Today I'm trying to navigate mongoose queries. Imagine we have a collection like this: [ {letter: "A", name: "Books", action: "read"}, {letter: "B", name: "Notebook", action: &q ...

Utilizing Javascript to Generate a Comma-Separated List from Multiple Select Elements

I have a set of dynamic single-option select elements that I need to work with. My goal is to generate a list containing the indexes of all selected options, separated by commas. Currently, I am using elements = document.getElementsByClassName("my-class ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

The action 'onDeleteClick' cannot be executed as the property is undefined

Why is the onDeleteClick function working on the first <div>, but returning undefined on the second one? I am able to access the reference of this, but when clicking, it shows "onDeleteClick of undefined". I am confused as to why the onDeleteClick f ...

"Troubleshooting: The Dropzone js code sample from the documentation

I am currently implementing a tutorial from the documentation provided by Dropzone.js. However, I seem to be encountering an issue as the example is not working correctly. Here is the structure that I currently have: Dropzone.options.myAwesomeDropzone = ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Retrieving data from a <span> element within a webpage created using ReactJS

I am completely new to the world of web design and development, so there may be some mistakes in my request. Essentially, I have a webpage that contains numerous span tags like the following example: These span tags are part of a significantly large DOM t ...