Browser Basics

Introduction

Understanding how the browser interacts with HTML, JavaScript, CSS, and other assets is like learning how to manage a complex orchestra. Each component—scripts, styles, images, fonts—plays a unique role in rendering a beautiful webpage. This guide will help you understand these fundamentals and equip you with the skills to create and manipulate web pages effectively.

Objectives

By the end of this lesson, you will be able to:

Running JavaScript in the Browser

Think of your browser as a theater. JavaScript acts like the script that directs actions on the stage. You can include JavaScript directly in HTML files using the <script> tag:

<script src="script.js"></script>

This imports the script file, allowing the browser to execute its contents. For instance, if you have a script that changes the background color, you can see it in action immediately when the HTML file is loaded.

Importing JavaScript from One File to Another

Modular JavaScript enables better code organization. By using export and import, you can reuse functions across files:

// utility.js
export function greet() {
    console.log('Hello!');
}

// main.js
import { greet } from './utility.js';
greet();

This is especially useful in larger projects, where separating concerns improves readability and maintainability.

How the Browser Loads Assets

Loading a webpage is like assembling a puzzle. The browser starts with the HTML, then fetches linked resources like CSS, JavaScript, images, and fonts. The process involves several steps:

  1. Parse HTML and build the DOM (Document Object Model).
  2. Load and apply CSS to construct the CSSOM (CSS Object Model).
  3. Fetch and execute JavaScript, which may modify the DOM or CSSOM.
  4. Render the final layout and paint it on the screen.

Node.js vs. Browser Environment

Running JavaScript in Node.js is like rehearsing a play backstage. It has access to different tools (e.g., file system, servers) but lacks the stage (browser DOM). In contrast, the browser provides visual elements (DOM) and browser-specific objects (e.g., window).

Executing JavaScript After Page Load

Use the DOMContentLoaded event to ensure all elements are ready before running your script:

document.addEventListener('DOMContentLoaded', () => {
    console.log('Page fully loaded!');
});

DOM vs. BOM

The DOM (Document Object Model) is the structured representation of the webpage, like a blueprint. The BOM (Browser Object Model) includes additional objects provided by the browser, like window, enabling interactions like opening a new tab or alerting the user.

Manipulating the BOM

You can manipulate BOM elements to create dynamic behaviors:

// Alert a message
window.alert('Welcome!');

// Log the current URL
console.log(window.location.href);