What Does the @run-at Directive Specify in Userscripts?

The @run-at directive in a userscript metadata block specifies the exact moment during the page loading process that the script should execute. By controlling whether a script runs before the page’s DOM starts loading, while it is building, or after the entire page and its external assets have finished loading, @run-at helps developers ensure their scripts run at the optimal time for performance and DOM availability.


Understanding the Common @run-at Values

Userscript managers (such as Tampermonkey, Violentmonkey, or Greasemonkey) support several predefined values for @run-at. Selecting the correct value depends on whether your code needs early access to interrupt page scripts or full access to the rendered HTML elements.

1. document-start

2. document-body

3. document-end

4. document-idle (Default)

5. context-menu


How to Set @run-at in Your Metadata Block

You declare @run-at inside the top metadata block of your userscript file alongside other directives like @name and @match.

// ==UserScript==
// @name         Custom Style Injector
// @namespace    http://tampermonkey.net/
// @version      1.0
// @match        https://example.com/*
// @run-at       document-start
// @grant        none
// ==UserScript==

// Your code runs immediately before the DOM starts parsing
console.log("Running at document-start!");

How to Choose the Right Setting