can-use-dom: Browser DOM Detection Utility

0.1.0 · abandoned · verified Sun Apr 19

This package provides a very minimalist utility to determine if the current JavaScript environment has access to the Document Object Model (DOM), primarily used for writing isomorphic (universal) JavaScript applications that need to behave differently client-side versus server-side. It exports a simple boolean value, `true` if `window`, `window.document`, and `window.document.createElement` are all defined, and `false` otherwise. The package is extremely lightweight with no dependencies. First released as version `0.1.0` and last updated over nine years ago, its development is considered abandoned. Due to its age, it primarily uses CommonJS module syntax, meaning direct native ESM imports may not function without a bundler or transpilation layer. Modern alternatives often include more sophisticated environment detection or rely on frameworks to abstract these differences. Its main differentiator is its absolute simplicity and singular focus, though its lack of maintenance makes it a less reliable choice for new projects.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use the `can-use-dom` boolean to conditionally execute browser-specific code.

const canUseDOM = require('can-use-dom');

if (canUseDOM) {
  console.log('Current environment supports DOM operations.');
  // Example: Manipulate the DOM if available
  const rootElement = document.getElementById('root');
  if (rootElement) {
    rootElement.innerHTML = '<h1>Hello from the browser!</h1>';
    console.log('DOM updated successfully.');
  }
} else {
  console.log('Current environment does NOT support DOM operations (e.g., Node.js server).');
  // Example: Server-side rendering logic or other non-DOM operations
  console.log('Performing server-side specific tasks...');
}

// To run this in Node.js, simply execute the file.
// To run this in a browser, embed it in an HTML script tag or use a bundler.

view raw JSON →