How is the @require tag used when developing userscripts?

The @require tag is a crucial metadata key used in userscript development to load external JavaScript libraries or scripts before your main code executes. By referencing a valid URL within the metadata block, it allows developers to seamlessly import powerful libraries like jQuery, React, or custom helper functions directly into their scripts. This overview explains the syntax, execution order, best practices, and common use cases for using @require in browser extensions like Tampermonkey or Violentmonkey.


Understanding the @require Syntax

To use external code in your userscript, you place the @require directive inside the ==UserScript== header block at the top of your file.

// ==UserScript==
// @name         Library Example Script
// @namespace    http://example.com
// @version      1.0
// @description  Demonstrating the @require tag
// @match        https://*.example.com/*
// @require      https://code.jquery.com/jquery-3.7.1.min.js
// @grant        none
// ==UserScript==

// Your custom script starts here and can use jQuery ($)
$('h1').css('color', 'red');

Key Rules and Functionality

Using the @require tag comes with specific execution rules and behavior that ensure your scripts run reliably:


Best Practices for Using @require

To keep your userscripts fast, secure, and reliable, consider these recommended guidelines: