🔍 JavaScript Utilities & Miscellaneous
Estimated reading: 4 minutes 51 views

⚙️ JavaScript – Lazy Loading, Printing, and Dialogs: Complete Guide with Examples


🧲 Introduction – Why These Features Matter in Modern Web Apps

Whether you’re optimizing load performance, enabling print views, or enhancing UX with native dialogs, these three JavaScript features—Lazy Loading, Printing, and Dialogs—are powerful tools every front-end developer should master.

By the end of this article, you’ll learn:

  • 💤 How to defer resource loading with Lazy Loading
  • 🖨️ How to generate and trigger Print Views
  • 💬 How to use built-in Dialog boxes (alert, confirm, prompt) and the modern <dialog> element

💤 Lazy Loading in JavaScript

✅ 1. What is Lazy Loading?

Lazy loading delays loading non-critical resources until they are needed (like images below the fold or heavy scripts). This boosts page speed and improves user experience.


✅ 2. Lazy Loading Images with HTML

<img src="thumbnail.jpg" loading="lazy" alt="Lazy Image Example" />

Explanation:

  • loading="lazy" tells the browser to load the image only when it’s about to appear in the viewport.

💡 Tip: Native lazy loading works in most modern browsers. Always provide a fallback for unsupported browsers.


✅ 3. Lazy Load with JavaScript and IntersectionObserver

const images = document.querySelectorAll("img[data-src]");

const observer = new IntersectionObserver((entries, obs) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src;
      obs.unobserve(img);
    }
  });
});

images.forEach(img => observer.observe(img));

Explanation:

  • IntersectionObserver watches when elements enter the viewport.
  • When visible, the real image URL (data-src) is assigned to src.

⚠️ Note: Always check if the browser supports IntersectionObserver.


🖨️ Printing Web Pages with JavaScript

✅ 1. Trigger Print Dialog

window.print();

Use case: One-click print button for invoices, receipts, or reports.


✅ 2. Add a Print Button

<button onclick="window.print()">🖨️ Print this page</button>

📘 Add this inside HTML where needed.


✅ 3. Print-Specific CSS (Best Practice)

@media print {
  body {
    font-size: 12pt;
  }
  .no-print {
    display: none;
  }
}

💡 Tip: Use .no-print classes to hide elements like nav bars, ads, or buttons during printing.


💬 JavaScript Dialogs – Built-in & Custom


✅ 1. alert(), confirm(), and prompt()

🔹 alert()

alert("Operation completed!");

✅ Shows a simple info dialog with OK button.


🔹 confirm()

if (confirm("Are you sure you want to delete this?")) {
  console.log("Deleted!");
}

✅ Returns true or false based on user action.


🔹 prompt()

const name = prompt("Enter your name:");
console.log("Hello, " + name);

✅ Accepts user input through a modal dialog.

⚠️ Warning: Native dialogs are blocking and halt script execution until dismissed.


✅ 2. Modern Dialogs using <dialog> Element

🔹 HTML

<dialog id="myDialog">
  <p>This is a custom dialog box.</p>
  <button id="closeBtn">Close</button>
</dialog>
<button id="openBtn">Open Dialog</button>

🔹 JavaScript

const dialog = document.getElementById("myDialog");
document.getElementById("openBtn").onclick = () => dialog.showModal();
document.getElementById("closeBtn").onclick = () => dialog.close();

Modern, non-blocking alternative to alert().

💡 Tip: <dialog> is customizable with CSS, unlike alert or confirm.


📊 Comparison Table

FeatureUse CaseBest MethodSupport
Lazy LoadingImage & resource optimizationloading="lazy" / IntersectionObserverModern browsers
Print ViewDocuments, reports, receiptswindow.print() + @media printAll browsers
Dialog BoxesAlerts, confirmations, inputs<dialog> or alert()/prompt()<dialog> = Modern

♿ Accessibility & Performance Tips

  • 💤 Lazy loading improves first paint and LCP (Largest Contentful Paint) for SEO.
  • 🖨️ Always design a print-specific layout to ensure proper formatting.
  • 💬 For <dialog>, use aria-label, tabindex, and focus trap to ensure accessibility.

✅ Summary – What You’ve Learned

In this article, you learned how to:

  • 💤 Use Lazy Loading to improve page speed by deferring image/resource loads
  • 🖨️ Add Print functionality with styled output using JavaScript and CSS
  • 💬 Implement JavaScript Dialogs from simple alerts to custom modal dialogs

These tools enhance performance, usability, and interactivity of any modern web app or dashboard.


❓ FAQ – Lazy Loading, Print, Dialogs in JavaScript

What is the easiest way to lazy load images in HTML?
👉 Use loading="lazy" in the <img> tag for native lazy loading.

Can I control what prints using CSS?
👉 Yes. Use @media print rules and add .no-print classes to hide elements like navbars or ads.

Are browser dialogs like alert() accessible?
👉 No. They’re not screen-reader friendly and block script execution. Prefer <dialog> with proper ARIA roles.

Is <dialog> supported in all browsers?
👉 Most modern browsers support it. For older ones, polyfills are available.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

JavaScript — Lazy Loading / Printing / Dialogs

Or Copy Link

CONTENTS
Scroll to Top