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:
- Execution Order: Required scripts are fetched, cached, and executed before your main userscript code runs.
- Sequential Loading: If you declare multiple
@requiretags, the script manager downloads and executes them in the exact order they appear in the metadata block. - Local Caching: Most userscript managers download the required file once upon script installation or update. It stores a local copy to improve performance and allow offline execution.
- Scope and Context: Required libraries execute within the same sandbox environment as your main userscript, giving your custom code direct access to any global variables or functions defined by the library.
Best Practices for Using @require
To keep your userscripts fast, secure, and reliable, consider these recommended guidelines:
- Use Direct CDN Links: Always point to a permanent, minified JavaScript file hosted on a reliable CDN (e.g., cdnjs, jsDelivr, or official library CDNs).
- Pin Specific Versions: Avoid referencing “latest”
or unversioned URLs. Use fixed version URLs (e.g.,
jquery-3.7.1.min.js) so unexpected library updates don’t break your script. - Leverage Subresource Integrity (SRI): Some advanced script managers support integrity checks to ensure the remote file has not been tampered with.
- Avoid Excessive Dependency: Keep required dependencies to a minimum to maintain fast script installation and load times.