DEV Community

Cover image for AltSchool Of Engineering Tinyuka’24 Month 5 Week 5
Ikoh Sylva
Ikoh Sylva

Posted on

AltSchool Of Engineering Tinyuka’24 Month 5 Week 5

We kicked off the class with a review of our previous session, which you can find here. Following that, we delved into an Overview of Document Resource Loading and much more!

Overview of Document Resource Loading

Managing resource loading in web pages is crucial for optimizing performance and user experience. Key events and attributes help control when scripts and resources are loaded, ensuring that the document is fully functional and responsive.

Page Lifecycle Events

1. DOMContentLoaded
This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, or subframes to finish loading. It’s an ideal point for executing scripts that manipulate the DOM.

Example:

document.addEventListener('DOMContentLoaded', () => { console.log('DOM fully loaded and parsed.'); }); 
Enter fullscreen mode Exit fullscreen mode

2. load
The load event occurs when the entire page, including all dependent resources (like stylesheets and images), has finished loading. This is useful for actions that require all resources to be available.

Example:

window.addEventListener('load', () => { console.log('All resources finished loading!'); }); 
Enter fullscreen mode Exit fullscreen mode

3. beforeunload and unload
These events are triggered when a user is about to leave the page. beforeunload can be used to prompt the user for confirmation, while unload occurs as the document is being unloaded.

Example:

window.addEventListener('beforeunload', (event) => { event.preventDefault(); event.returnValue = ''; // Display a confirmation dialog }); 
Enter fullscreen mode Exit fullscreen mode

Script Loading

1. async
Scripts with the async attribute load asynchronously, meaning they can be fetched in parallel without blocking the page rendering. The script will execute as soon as it is available.

Example:

<script src="script.js" async></script> 
Enter fullscreen mode Exit fullscreen mode

2. defer
The defer attribute also allows scripts to load in the background, but ensures they execute in the order they are found in the document after the HTML has been fully parsed.

Example:

<script src="script.js" defer></script> 
Enter fullscreen mode Exit fullscreen mode

3. Dynamic Scripts
Scripts can also be added dynamically using JavaScript, allowing for more control over loading and execution.

Example:

const script = document.createElement('script'); script.src = 'dynamicScript.js'; document.head.appendChild(script); 
Enter fullscreen mode Exit fullscreen mode

Resource Loading Events

For elements like <img>, <script>, <link>, and <style>, the onload and onerror events can be used to handle successful loading and errors, respectively.

Example for an image:

const img = document.createElement('img'); img.src = 'image.jpg'; img.onload = () => { console.log('Image loaded successfully!'); }; img.onerror = () => { console.log('Error loading image.'); }; document.body.appendChild(img); 
Enter fullscreen mode Exit fullscreen mode

Understanding Web APIs

Web APIs enable developers to interact with browser functionality and enhance user experiences. Here’s an overview of some essential features and capabilities.

Frames and Windows

Managing multiple windows and frames can improve user interaction but also poses challenges like clickjacking. Key concepts include:

  • Popups and Window Methods: Functions like window.open() and window.close() allow for creating and managing new browser windows.

  • Cross-Window Communication: Techniques such as the postMessage method facilitate secure communication between windows or iframes, ensuring data can be shared safely.

Example of using postMessage:

// In the child window window.opener.postMessage('Hello from child!', '*'); 
Enter fullscreen mode Exit fullscreen mode

Binary Data and the File API

The File API provides ways to handle binary data in web applications. Key components include:

  • ArrayBuffer: A generic, fixed-length binary data buffer.

  • Blob: Represents immutable raw binary data.

  • File: A specific type of Blob, representing file data from user inputs.

  • FileReader: A utility to read file data asynchronously.
    Common methods include:

  • readAsArrayBuffer(): Reads the contents of a file as an ArrayBuffer.

  • readAsText(): Reads the file as plain text.

  • readAsDataURL(): Reads the file and encodes it as a base64 data URL.
    Example of reading a file:

const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = () => { console.log(reader.result); // File content }; reader.readAsText(file); }); 
Enter fullscreen mode Exit fullscreen mode

Storing Data in the Browser

The browser provides several options for storing data:

  • Cookies: Small pieces of data stored in document.cookie, useful for session management.

  • localStorage: Provides a way to store key-value pairs persistently across sessions.

  • sessionStorage: Similar to localStorage but clears when the session ends.

  • IndexedDB: A more complex storage system for structured data, often accessed using libraries like Dexie.js for easier management.

Example of using localStorage:

localStorage.setItem('username', 'JohnDoe'); console.log(localStorage.getItem('username')); // Outputs: JohnDoe 
Enter fullscreen mode Exit fullscreen mode

Animation

Creating animations enhances user experience and engagement. Key concepts include:

  • Bezier Curves: Used to define smooth transitions in animations.

  • CSS Animations: Allows for animations defined in stylesheets, providing a simple and efficient way to animate elements.

  • JavaScript Animations: Offers more control and flexibility for complex animations.

  • requestAnimationFrame: A method that allows the browser to optimize animations by syncing them with the refresh rate.
    Example of a simple animation using requestAnimationFrame:

let start = null; function animate(timestamp) { if (!start) start = timestamp; const progress = timestamp - start; // Update the animation based on progress if (progress < 2000) { requestAnimationFrame(animate); } } requestAnimationFrame(animate); 
Enter fullscreen mode Exit fullscreen mode

Introduction to Web APIs

Web APIs are essential tools that facilitate interaction between JavaScript and the browser's built-in functionalities. They enable developers to create rich, interactive web applications by providing a structured interface to various browser features.

Image of someone working on her PC

What Are Web APIs?

Web APIs serve as JavaScript interfaces that allow web applications to utilize browser capabilities. This includes everything from manipulating the Document Object Model (DOM) to accessing hardware features, enhancing user engagement and experience.

Categories of Web APIs

1. DOM APIs
These APIs allow for dynamic manipulation of HTML and XML documents. For instance, you can add, remove, or modify elements within a webpage.

Example:

const element = document.createElement('div'); element.textContent = 'Hello, World!'; document.body.appendChild(element); 
Enter fullscreen mode Exit fullscreen mode

2.Storage APIs
These provide client-side data persistence solutions, including localStorage and sessionStorage for storing key-value pairs, as well as IndexedDB for more complex data structures.

Example:

localStorage.setItem('theme', 'dark'); console.log(localStorage.getItem('theme')); // Outputs: dark 
Enter fullscreen mode Exit fullscreen mode

3. Network APIs
These APIs enable communication with servers using methods like fetch() for making requests and handling responses.

Example:

fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)); 
Enter fullscreen mode Exit fullscreen mode

4. Media APIs
These APIs manage audio and video playback, allowing developers to create rich multimedia experiences.

Example:

const video = document.querySelector('video'); video.play(); // Starts playing the video 
Enter fullscreen mode Exit fullscreen mode

5. Device APIs
These provide access to hardware features such as geolocation, camera, and sensors, enabling applications to interact with the user's device.

Example:

navigator.geolocation.getCurrentPosition(position => { console.log(position.coords.latitude, position.coords.longitude); }); 
Enter fullscreen mode Exit fullscreen mode

6. Security APIs
These APIs facilitate cryptography and authentication processes, ensuring secure interactions and data protection.
Key Features of Web APIs

  • Asynchronous Operations: Many Web APIs support asynchronous operations using Promises and the async/await syntax, allowing for non-blocking code execution.

Example:

async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); console.log(data); } 
Enter fullscreen mode Exit fullscreen mode
  • Event-Driven Programming: Web APIs often utilize an event-driven model, enabling applications to respond to user interactions and other events efficiently.

  • Cross-Origin Security: Web APIs implement security measures to handle cross-origin requests, protecting against unauthorized access and data leakage.

  • Progressive Enhancement: This principle allows developers to create applications that work on a basic level across all browsers while enhancing functionality in modern environments.

Understanding Security in Web Applications

Security is a critical aspect of web development, particularly when dealing with frames and windows. The security model ensures that scripts operate safely, protecting users from potential malicious activities.

Security Model and Same-Origin Policy

The Same-Origin Policy (SOP) is a fundamental security mechanism in web browsers that restricts how documents or scripts from one origin can interact with resources from another origin. An origin is defined by the combination of protocol, domain, and port (e.g., https://example.com:443).

  • Purpose of SOP: This policy prevents unauthorized access to data from different origins, safeguarding against cross-site scripting (XSS) attacks and data leaks.

Binary Data and the File API

The File API provides a structured way to handle binary data in web applications. It includes several core components:

  1. File: Represents information about a file, such as its name, type, and size.

Example:

const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; console.log(`File name: ${file.name}, File size: ${file.size}`); }); 
Enter fullscreen mode Exit fullscreen mode
  1. FileReader: A powerful interface that allows web applications to read the contents of files asynchronously. It can read files as text, binary data, or data URLs.

Example:

const reader = new FileReader(); reader.onload = () => { console.log(reader.result); // Outputs the file's content }; reader.readAsText(file); // Reads the file as text 
Enter fullscreen mode Exit fullscreen mode
  1. Blob: A Blob (Binary Large Object) represents raw data in a file-like object. Blobs can hold data that isn't necessarily in a JavaScript-native format.

Example:

const blob = new Blob(['Hello, World!'], { type: 'text/plain' }); 
Enter fullscreen mode Exit fullscreen mode
  1. ArrayBuffer: This object represents a generic, fixed-length binary data buffer. It is useful for handling raw binary data directly.

Example:

const buffer = new ArrayBuffer(16); // Creates a buffer of 16 bytes 
Enter fullscreen mode Exit fullscreen mode

Reading Files

The File API's capabilities allow developers to implement file reading features in their applications, making it easier to handle user-uploaded files securely and efficiently.

Animation Principles

Creating smooth animations is a key aspect of modern web development. Effective animations enhance user experience by providing visual feedback and engaging interactions.

Using requestAnimationFrame

The requestAnimationFrame method is a powerful tool for implementing animations in JavaScript. It offers several advantages:

  • Smooth Rendering: By aligning the animation updates with the browser’s refresh rate, requestAnimationFrame facilitates rendering at approximately 60 frames per second (fps), resulting in fluid motion.

  • Performance Optimization: The method automatically pauses when the browser window is hidden, preventing unnecessary processing and conserving resources.

Example of JavaScript Animation

Here’s a simple demonstration of how to use requestAnimationFrame to create a smooth animation:

let posX = 0; const element = document.querySelector('.animate'); function animate() { posX += 2; // Update position element.style.transform = `translateX(${posX}px)`; // Move the element if (posX < window.innerWidth) { requestAnimationFrame(animate); // Continue the animation } } 
Enter fullscreen mode Exit fullscreen mode

requestAnimationFrame(animate); // Start the animation
In this example, an element moves horizontally across the screen. The use of requestAnimationFrame ensures that the animation is smooth and efficient.

Image of a lady working on her laptop

I’m Ikoh Sylva, a passionate cloud computing enthusiast with hands-on experience in AWS. I’m documenting my cloud journey from a beginner’s perspective, aiming to inspire others along the way.

If you find my content helpful, please like and follow my posts, and consider sharing this article with anyone starting their own cloud journey.

Let’s connect on social media. I’d love to engage and exchange ideas with you!

LinkedIn Facebook X

Top comments (0)