CSS for When JavaScript Is Enabled

Master the scripting media feature for progressive enhancement and build resilient web experiences that work for everyone

The Scripting Media Feature

Modern web development has evolved significantly, and one of the most powerful yet underutilized features in CSS today is the ability to detect whether JavaScript is enabled in the user's browser. This capability, supported across all modern browsers since December 2023, opens up new possibilities for progressive enhancement, accessibility, and performance optimization.

The scripting media feature is part of the CSS Media Queries Level 5 specification and provides a native way to detect JavaScript availability directly in your stylesheets. By leveraging this feature, you can create highly nuanced experiences that adapt not just to whether JavaScript works, but to the specific way it operates in the user's environment.

This approach aligns with our philosophy at Digital Thrive: build robust, accessible experiences that work for everyone, then layer enhancements on top for users with more capable browsers. The result is websites that are faster, more resilient, and inclusive of all users regardless of their browser configuration.

Understanding the Three Values

The scripting media feature returns three possible values for different scripting states

enabled

Matches when JavaScript is available and active in the browser

none

Matches when scripting is completely disabled or unavailable

initial-only

For scripting enabled during page load but disabled afterward

Basic Syntax and Usage

The syntax for using the scripting media feature is straightforward and follows the same pattern as other media queries you've likely used before:

@media (scripting: enabled) {
 /* Enhanced styles when JavaScript is available */
 .animated-element {
 opacity: 1;
 transform: translateY(0);
 }
}

@media (scripting: none) {
 /* Fallback styles when JavaScript is disabled */
 .animated-element {
 opacity: 1;
 transform: none;
 }
}

The first block applies enhanced styles when JavaScript is active, while the second block provides fallback styles for users who have disabled JavaScript or are browsing with scripting completely unavailable. This pattern ensures your site remains functional and visually consistent regardless of JavaScript availability, a core principle of modern web development practices.

For more information on feature detection in CSS, refer to MDN's documentation on feature detection.

Progressive Enhancement Pattern
1/* Base styles - work everywhere */2.accordion-item {3 border-bottom: 1px solid #e5e5e5;4}5 6.accordion-header {7 padding: 1rem;8 cursor: pointer;9}10 11/* Enhanced styles when JavaScript is available */12@media (scripting: enabled) {13 .accordion-item {14 transition: background-color 0.2s ease;15 }16 17 .accordion-header::after {18 content: '+';19 float: right;20 }21 22 .accordion-content {23 max-height: 0;24 overflow: hidden;25 }26}

Progressive Enhancement Pattern

One of the most powerful applications of the scripting media feature is the progressive enhancement pattern. Instead of building complex JavaScript-dependent functionality and hoping it works everywhere, you start with a solid baseline experience that works for everyone, then layer enhancements on top.

This approach ensures that all users can access your content, while those with JavaScript enabled get additional polish and interactivity. The GOV.UK Service Manual emphasizes that progressive enhancement is essential for building robust, accessible digital services that work for everyone.

The key insight is that your base styles should always provide a complete, usable experience. Enhanced styles are exactly that--an enhancement, not a requirement. This philosophy leads to better performance, improved accessibility, and more resilient code overall.

Practical Implementation Examples

Animation Enhancement

A common use case for the scripting media feature is enhancing animations and transitions when JavaScript is available:

/* Base animation - works without JS */
@keyframes fadeIn {
 from { opacity: 0; }
 to { opacity: 1; }
}

.hero-title {
 animation: fadeIn 1s ease-out;
}

/* Enhanced animation when JS is available */
@media (scripting: enabled) {
 .hero-title {
 animation: fadeIn 1s ease-out, slideUp 0.5s ease-out;
 animation-delay: 0.2s;
 }
 
 .hero-subtitle {
 animation: fadeIn 1s ease-out;
 animation-delay: 0.5s;
 }
}

This pattern allows you to add complexity and visual interest without breaking the experience for users without JavaScript. As demonstrated in Ryan Mulligan's guide to detecting JavaScript support in CSS, this technique is particularly valuable for creating layered animation experiences that gracefully degrade.

When implementing animations, always consider users who prefer reduced motion--combine the scripting media feature with prefers-reduced-motion to respect accessibility preferences while still providing enhanced experiences for those who want them. This attention to accessibility details is a hallmark of professional web development services that prioritize inclusive design.

Preventing Flash of Unstyled Content

One particularly valuable application is preventing the "flash of unstyled content" (FOUC) that can occur when JavaScript-dependent styles load after the initial render:

/* Hide enhanced content by default */
.js-enhanced-content {
 display: none;
}

/* Show when JavaScript is available */
@media (scripting: enabled) {
 .js-enhanced-content {
 display: block;
 animation: contentReveal 0.3s ease-out;
 }
}

This technique ensures that users without JavaScript don't see empty containers or broken layouts while waiting for scripts to load. According to MDN's CSS and JavaScript accessibility guidelines, this approach significantly improves the perceived performance and professionalism of your website.

For complex applications, consider extending this pattern to include smooth transitions that reveal content only when it's fully loaded and ready, creating a polished experience that avoids the jarring visual glitches that can damage user trust. Proper FOUC prevention also contributes to better search engine optimization by ensuring crawlers can access content immediately.

Combining with Other Media Queries

The true power of the scripting media feature emerges when combined with other media queries.

Respecting Motion Preferences

Many users prefer reduced motion due to vestibular disorders. The prefers-reduced-motion media query works alongside scripting:

@media (scripting: enabled) and (prefers-reduced-motion: no-preference) {
 .animated-element {
 animation: complexAnimation 2s ease-in-out infinite;
 }
}

@media (scripting: none), (prefers-reduced-motion: reduce) {
 .animated-element {
 opacity: 1;
 transform: none;
 }
}

This layered approach ensures that motion-sensitive users are never subjected to animations, regardless of whether JavaScript is enabled, while still providing an enhanced experience for users who want both motion and scripting. As Ryan Mulligan illustrates in his comprehensive guide, combining these media queries creates truly adaptive user experiences.

Dark Mode Considerations

The scripting media feature also combines effectively with color scheme preferences:

@media (scripting: enabled) and (prefers-color-scheme: dark) {
 .card {
 background-color: #2d2d2d;
 box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
 }
}

This allows you to provide enhanced styling when users have both JavaScript enabled and prefer dark mode, creating sophisticated theme experiences that respect multiple user preferences simultaneously.

Legacy Approaches and Modern Comparison

Before the scripting media feature was widely supported, developers used various workarounds to detect JavaScript availability. The most common approach involved setting a class on the HTML element and using JavaScript to change it:

<html class="no-js">
document.documentElement.classList.remove('no-js');
document.documentElement.classList.add('js');
.no-js .enhanced-feature {
 /* Fallback styles */
}

.js .enhanced-feature {
 /* Enhanced styles */
}

While this approach still works and remains useful for certain scenarios, the scripting media feature offers several significant advantages. It's purely declarative in CSS, requires no JavaScript execution to detect scripting availability, and works even if JavaScript fails to load or execute due to network issues, script blocking, or errors.

As noted in Ryan Mulligan's analysis, the modern approach eliminates the race condition where JavaScript might not execute before styles are applied, providing a more reliable foundation for progressive enhancement strategies. This is particularly valuable for AI-powered automation solutions that depend on reliable JavaScript detection patterns.

Performance Considerations

Using the scripting media feature for progressive enhancement isn't just about user experience--it also has meaningful performance implications.

Reduced JavaScript Dependency

When you use CSS to handle enhancement logic, you reduce the amount of JavaScript required for your page:

  • Smaller bundle sizes and faster initial load times
  • Less JavaScript parsing and execution on the main thread
  • Reduced impact on Time to Interactive (TTI)
  • Better performance on low-powered devices

Conditional Loading Pattern

For complex sites, consider using separate stylesheets loaded conditionally:

<link rel="stylesheet" href="core.css">
<link rel="stylesheet" href="enhanced.css" media="(scripting: enabled)">

This approach, recommended by MDN's accessibility documentation, ensures users without JavaScript only download the essential styles, while users with JavaScript get the enhanced experience.

By reducing unnecessary JavaScript execution, you improve Core Web Vitals metrics like Largest Contentful Paint and First Input Delay, which are critical factors in both user experience and search engine rankings. Implementing these performance optimizations is a key part of our web development methodology.

Accessibility Best Practices

When implementing JavaScript-dependent enhancements with CSS, several accessibility considerations should guide your approach.

Maintain Core Functionality

Every enhancement should have a functional fallback. If JavaScript is required for critical functionality, consider providing alternative navigation methods, ensuring form submissions work without JavaScript, and making sure interactive elements remain accessible via keyboard.

Respect User Preferences

The prefers-reduced-motion media query should always take precedence over your animation enhancements. Additionally, respect prefers-contrast for users who need higher contrast and prefers-reduced-transparency for users who may have difficulty with transparent elements.

Progressive Disclosure Patterns

When using the scripting media feature for progressive disclosure, ensure that hidden content is accessible to assistive technologies when relevant, keyboard navigation remains logical and predictable, and ARIA attributes are used appropriately to communicate state changes.

As MDN emphasizes, CSS and JavaScript, when used properly, have the potential to enable accessible web experiences, or can significantly harm accessibility if misused. The scripting media feature gives you the tools to get it right. Accessibility is not just a technical requirement--it's fundamental to creating inclusive digital experiences that serve all users effectively.

Common Use Cases

Animation Enhancement

Layer complex animations on top of simple CSS animations for enhanced visual appeal

FOUC Prevention

Hide JavaScript-dependent components until they're ready to prevent visual glitches

Progressive Disclosure

Show additional content or controls only when scripting is available

Layout Adaptation

Provide different layouts based on scripting availability and user preferences

Conclusion

The scripting CSS media feature represents a significant advancement in how we approach progressive enhancement for modern web applications. By providing a native, declarative way to detect JavaScript availability, it enables developers to build robust, accessible experiences that work for everyone while providing enhanced functionality for users with JavaScript enabled.

As browser support is now universal across modern browsers, there's no reason not to leverage this feature in your projects. Start by identifying areas where you can layer enhancements on top of solid baselines, and gradually expand your use of the scripting media feature to create more sophisticated, adaptive user experiences.

The key principle to remember is that CSS and JavaScript should work together, not compete. Use the scripting media feature to create clear boundaries between what works everywhere and what works with JavaScript enhancement, and you'll build more resilient, performant, and accessible websites. The GOV.UK guidance on progressive enhancement reinforces this philosophy as essential for building digital services that serve all users effectively.

Ready to implement progressive enhancement patterns in your web projects? Our web development team specializes in building performant, accessible websites that leverage modern CSS techniques for optimal user experiences.

Ready to Build Modern Web Experiences?

Our team specializes in progressive enhancement patterns and modern CSS techniques for performant, accessible websites.

Frequently Asked Questions

Sources

  1. Ryan Mulligan - Detect JavaScript Support in CSS - Comprehensive guide on the scripting media feature with practical examples
  2. MDN Web Docs - Feature Detection - Official documentation on @supports and CSS feature detection
  3. MDN Web Docs - CSS and JavaScript Accessibility - Best practices for accessible CSS and JavaScript implementation
  4. MDN - Progressive Enhancement Glossary - Core philosophy and principles of progressive enhancement
  5. GOV.UK - Building Robust Frontend with Progressive Enhancement - Government digital service guidelines for progressive enhancement