Environment is browser

JavaScript, Browser · Oct 20, 2020

Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

  • Use Array.prototype.includes() on the typeof values of both Window and Document (globals usually only available in a browser environment unless they were explicitly defined), which will return true if one of them is undefined.
  • typeof allows globals to be checked for existence without throwing a ReferenceError.
  • If both of them are not undefined, then the current environment is assumed to be a browser.
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
isBrowser(); // true (browser)
isBrowser(); // false (Node)

More like this

  • Run function asynchronously

    Runs a function in a separate thread by using a Web Worker.

    JavaScript, Browser · Oct 22, 2020

  • NodeList to array

    Converts a NodeList to an array.

    JavaScript, Browser · Oct 21, 2020

  • Listen for an event only once

    Adds an event listener to an element that will only run the callback the first time the event is triggered.

    JavaScript, Browser · Oct 22, 2020