Home » Hooks » script_loader_src

The WordPress hook script_loader_src is a powerful tool that allows developers to modify or replace the source URL of any registered script in WordPress. This hook is fired whenever a script is enqueued, providing an opportunity to dynamically change the source URL before it is loaded on the webpage.

The script_loader_src hook is used primarily to manipulate the URL of scripts in order to customize or optimize their loading behavior. This can include scenarios such as changing the source URL to a local file, adding query parameters, or even completely replacing the script with a different one.

One common use case for script_loader_src is to implement a custom CDN (Content Delivery Network) for scripts. By using this hook, developers can redirect the source URL of a script to their own CDN, improving performance by loading the script from a faster and geographically closer server.

Example Usage:

function custom_script_cdn($src, $handle) {
    if ($handle === 'jquery') {
        $src = ''; // Replace with your CDN URL
    return $src;
add_filter('script_loader_src', 'custom_script_cdn', 10, 2);

In this example, the callback function custom_script_cdn is hooked onto script_loader_src using the add_filter function. The function takes two parameters: $src, which represents the original source URL of the script, and $handle, which is the unique handle used to register the script. The callback checks if the script handle is ‘jquery’ and if so, replaces the source URL with a custom CDN URL. Finally, the modified source URL is returned by the callback function.

By utilizing the script_loader_src hook, developers have the flexibility to modify script URLs on-the-fly, enabling them to optimize and customize the loading process for enhanced website performance and functionality.

Learn More on

WordPress snippets using the script_loader_src hook

Register an account to save your snippets or go Pro to get more features.