JavaScript Environment

Explore JavaScript scope, starting from the global scope to the local scope, and learn how to declare and use variables in different scopes.

Purpose

JavaScript is a versatile programming language that can be used to create interactive elements on a web page. Understanding the scope of variables in JavaScript is essential for writing efficient and maintainable code.

1. DOMContentLoaded Event:

  1. What it is: The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
  2. Purpose: Useful if you want to execute a script after the HTML has been fully parsed but before the entire page (including images, etc.) has been fully loaded.
document.addEventListener("DOMContentLoaded", function() {
    // Code to run when the DOM content is fully loaded
  });

2 . window.onload Event:

The window.onload event is triggered when the entire page, including all dependent resources such as images, iframes, and stylesheets, has fully loaded. This is different from DOMContentLoaded, which only waits for the HTML to be parsed and does not wait for external resources.

Differences Between DOMContentLoaded and window.onload:

DOMContentLoaded Fires when the initial HTML document is completely loaded and parsed, without waiting for stylesheets, images, or subframes.

window.onload: Fires only after the entire content of the page has been loaded, including images, scripts, and stylesheets.

Purpose Use window.onload when you need to ensure that all external resources (such as images and CSS files) are fully loaded before executing your JavaScript code.

<body>
    <script>
        // Attaching a window.onload event
        window.onload = function() {
            console.log("Entire page including resources has been loaded.");

            // Example: Dynamically change an image source after the page loads
            const img = document.querySelector('#myImage');
            if (img) {
                img.src = '/path/to/new/image.jpg';
            }
        };
    </script>

    <img id="myImage" src="/path/to/initial/image.jpg" alt="Example Image" />
</body>

When to Use: Use window.onload when your script relies on fully loaded resources, such as images or iframes. Use DOMContentLoaded when you only need the HTML to be parsed before executing your script, making it suitable for faster execution without waiting for resources.

3. async Attribute in <script> Tag:

  1. Loading: The script is fetched asynchronously (in parallel with the HTML parsing), but its execution happens as soon as the script is downloaded. This can disrupt the order of execution of scripts since the script may execute before or after other scripts.
  2. When to use: Best for scripts that do not rely on the DOM or on each other, such as analytics scripts.
  3. Execution order: No guarantee of execution order if there are multiple scripts with async.
<script async src="script.js"></script>

4. defer Attribute in <script> Tag:

  1. Loading: The script is fetched asynchronously (in parallel with the HTML parsing), but execution happens only after the HTML document has been fully parsed (i.e., when the DOMContentLoaded event is about to fire).
  2. When to use: Useful for scripts that rely on the DOM being fully available, but should not block the parsing of the HTML document.
  3. Execution order: Scripts with defer are executed in the order they appear in the document.
<script defer src="script.js"></script>

Global Scope

To load your own JavaScript code, you can use the head or body section of your HTML document. You can declare variables and functions in the global scope, which are accessible from anywhere in the script.

The Difference Between Loading in the head and body Sections: When you load your JavaScript code in the head section, the script is executed before the HTML content is loaded. If you load your JavaScript code in the body section, the script is executed after the HTML content is loaded, which is the normal behavior for most scripts.

Loading JavaScript Code in the head Section

<head>
      <title>Global Scope Example</title>
      <script src="<?= Request::baseUrl; ?>/js/custom.js"></script>
  </head>

Note: The head section is typically used to load external resources such as stylesheets, scripts, and metadata. It is recommended to load JavaScript code in the head section to ensure that the script is executed before the HTML content is loaded. This is especially important for Prisma PHP, as it updates the title, meta description, and body content, which can improve page load speed and prevent any issues with script execution.

Loading JavaScript Code in the body Section

<body>
      <h1>Global Scope Example</h1>
      <script src="<?= Request::baseUrl; ?>/js/index.js"></script>
  </body>

Note: The body section is typically used to load scripts that interact with the HTML content. By loading the script in the body section, you ensure that the script is executed after the HTML content is loaded, allowing it to interact with the elements on the page. You can use the Request class to get the baseUrl, which will return the path src/app. Alternatively, you can directly use src/app/your-path. Prisma PHP will create a new instance of the script and execute it after the HTML content is loaded, making it easier to interact with the elements on the page. This allows you to load your own dynamic script in different sections of the page and make it interact with the elements on the page.

Global scope

Variables declared outside of any function are considered global variables and can be accessed from anywhere in the script. Global variables are not recommended because they can be modified by any part of the script, leading to unexpected behavior.

<head>
      <title>Global Scope Example</title>
      <script>
          // Global scope
          var globalVariable = "I am a global variable";
  
          function globalFunction() {
              console.log(globalVariable);
          }
      </script>
  </head>
  <body>
      <h1>Check the console for global variable output</h1>
      <script>
          // Accessing global variable and function
          console.log(globalVariable);
          globalFunction();
      </script>
  </body>

Local Scope (Default Scope)

<body>
    <script>
      // Local scope using an immediately invoked function expression (IIFE) default scope in Prisma PHP
      (function () {
        var localVariable = "I am a local variable";
  
        function localFunction() {
          console.log(localVariable);
        }
  
        // Call the function within the local scope
        localFunction();
      })();
  
      // Trying to access localVariable or localFunction here would result in an error
      // console.log(localVariable); // Uncaught ReferenceError: localVariable is not defined
      // localFunction(); // Uncaught ReferenceError: localFunction is not defined
    </script>
  </body>

DOMContentLoaded

<body>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            // Global scope
            var globalVariable = "I am a global variable";

            // Local scope
            let letVariable = "I am a local variable";

            // Local scope
            const constVariable = "I am a constant variable";
        
            function globalFunction() {
                console.log(globalVariable);
            }

            // Call the global function within DOMContentLoaded
            globalFunction();
        });
    </script>
  </body>