Explain Codes LogoExplain Codes Logo

Is there a HTML opposite to ?

html
accessibility
dynamic-content
user-experience
Nikita BarsukovbyNikita Barsukov·Aug 15, 2024
TLDR

To essentially create an inline JavaScript equivalent of <noscript> for when JavaScript is enabled, you can insert content dynamically as follows:

document.addEventListener('DOMContentLoaded', (event) => { // Joe: "Hey JavaScript, can you speak?" // JavaScript: "<strong>I am active!</strong>" document.body.innerHTML += '<strong>Javascript is active!</strong>'; });

This JavaScript snippet is activated as soon as the DOM is fully loaded, inserting content to announce that JavaScript is running. It's an efficient and quick way to create content linked directly to the operation of your script.

Focusing on compatibility and functionality

Implementing conditional content display

A handy way to control the display of content based on JavaScript is with CSS:

.jsOff { display: none; }

You can tag any element with this .jsOff class, and should JavaScript be enabled, it can be deleted:

document.documentElement.classList.remove('jsOff');

Coordinating <noscript> and <style>

A clever trick is to combine the <style> tag with <noscript> to provide a fallback design scheme:

<noscript> <style> .jsOnly { display: none; } </style> </noscript>

By tagging elements with the .jsOnly class, they'll only show up when JavaScript is running, essentially giving you a 'yes-script' behaviour.

Dynamic content: Load as needed

JavaScript's event-driven model supports dynamic content injection:

window.onload = function() { // Joe: "JavaScript, can you make magic content appear?" // JavaScript: "Sure, hold my semicolon..." document.querySelector('.jsOnly-content-placeholder').innerHTML = '<div>Interactive content loaded</div>'; };

Prioritizing accessibility and structure

Serious about accessibility? Always have a <noscript> fallback for non-JavaScript scenarios. For organization, maintain a clear division and arrangement of HTML content.

Boosting performance and UX

Ensure a smoother user experience by having JavaScript preload content. User experience is greatly improved when JavaScript-dependent pages load quickly and seamlessly.

Avoiding outdated practices

document.write() is like using Windows XP in 2022, so avoid it. For a robust structure and better maintainability, adopt more refined methods like createElement and appendChild.