Programmatically Modifying Enqueued Script Tags In WordPress

The Problem of Enqueued Scripts

Enqueued scripts in WordPress refer to external JavaScript files that are loaded onto a WordPress site using the wp_enqueue_script() function. This loads the script file onto the page by inserting a script tag that references the file location.

Modifying these enqueued scripts can be useful for several reasons:

  • Combining multiple scripts into one file can reduce HTTP requests and improve page load speed
  • Forcing script reloads by changing the script version
  • Updating jQuery or other library versions site-wide
  • Removing unused script code to reduce bloat
  • Modifying script behaviour with custom code

However, modifying enqueued scripts can also lead to issues if not done properly:

  • Plugin and theme compatibility problems
  • JavaScript errors if dependencies are broken
  • Caching issues leading to old script versions loading

In this article we’ll explore the proper way to programmatically modify enqueued script tags in WordPress to avoid issues and achieve site improvements.

Finding the Scripts You Want to Modify

The first step in programmatically modifying enqueued scripts is to identify the handles and sources of the scripts you wish to change. There are two main ways to achieve this in WordPress:

Using wp_scripts()

The wp_scripts() function returns an array containing all scripts currently enqueued on the page. You can print_r() or var_dump() this array to inspect it:

$scripts = wp_scripts();
print_r($scripts);

This will show all currently enqueued scripts with their handles and sources. Some other details visible here include dependencies, versions, and location in header or footer.

Using wp_enqueue_script()

The most common way that scripts get enqueued is by various plugins and themes running the wp_enqueue_script() function. By searching through these calls you can find scripts handles and sources.

Some good places to check include:

  • Your theme’s functions.php file
  • The plugin files of plugins you have enabled
  • Inside hooks like enqueue_scripts and admin_enqueue_scripts actions

By studying these enqueue scripts calls you can target scripts to modify.

Identifying Script Handles and Sources

Once you’ve located some scripts you want to modify, take note of their handles and sources:

  • Handles – A unique ID that identifies the script, used as an identifier for script dependencies and calling code.
  • Sources – The URL location of the external JavaScript file that should be loaded.

As an example, jQuery scripts in WordPress often use a handle of “jquery” and source of “//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js”.

The handles and sources will be important identifiers for actually applying script modifications covered next.

Modifying Script Attributes

The easiest way to modify enqueued scripts is to change various script “attributes” when calling wp_enqueue_script(). This allows tweaking certain properties like dependencies and locations without altering any code.

Script Dependencies

You can add or remove dependencies for enqueued scripts like so:

function modify_scripts(){

  wp_enqueue_script( 'script-handle', 'script-source', array( 'dep-handle1', 'dep-handle2') );

}
add_action('wp_enqueue_scripts','modify_scripts');

This can be useful for concatenating scripts by making one script depend on another to combine the files (covered more later).

Script Versions

Another easy change is modifying the script version:

function modify_scripts(){

  wp_enqueue_script( 'script-handle', 'script-source', array(), '1.1' );

}
add_action('wp_enqueue_scripts','modify_scripts');  

Changing the version forces a script reload which can be used to fix caching issues. Just incrementing the version works well.

Script Locations

Scripts can also be moved from their existing location (header or footer) like so:

function modify_scripts(){

  wp_enqueue_script( 'script-handle', 'script-source', array(), null, true );

}
add_action('wp_enqueue_scripts','modify_scripts');

The last true parameter forces the script to load in the document footer. Default is header.

Modifying Script Content

In addition to attributes, the actual content of enqueued scripts can also be modified on the fly before output to the browser.

Replacing/Updating Script Content

You can replace the entire contents of a script by dequeuing the original and re-enqueuing your custom version:

 
function replace_script(){

  wp_dequeue_script( 'original-handle' ); //remove original 
  
  wp_register_script('custom-handle', 'custom-source', array('jquery')); //register custom script

  wp_enqueue_script('custom-handle'); //enqueue custom script

}
  
add_action('wp_print_scripts', 'replace_script', 100);

Helpful for replacing library versions or inserting your own debug code.

Removing Parts of a Script

More granular content changes can be done by removing just parts of an enqueued script:

function filter_script_content($content){

    if(stripos($content, 'alert') !== false)){
        $content = str_replace('alert','console.log', $content); //replace alerts
    }

    return $content;

}
 
add_filter('script_loader_tag', 'filter_script_content', 10, 2); 

Good for eliminating unused code and slimming down scripts.

Concatenating Scripts

The best way to combine multiple scripts into one file is through dependencies and a concatenation callback:

function concat_scripts($tag, $handle){

    if ('combined-handle' !== $handle)
        return $tag;

    $scripts = array('script1', 'script2');

    $src = '';

    foreach ($scripts as $script) {
      $src .= wp_scripts()->registered[$script]->src;
    }

    $tag = '';
    
    return $tag;
}
add_filter('script_loader_tag', 'concat_scripts', 20, 2);

function enqueue_concat_scripts(){
  
  wp_enqueue_script('combined-handle', false, $scripts, '', true );

}
add_action('wp_enqueue_scripts', 'enqueue_concat_scripts');

This allows merging JS files, avoiding additional HTTP requests.

Practical Examples

Some practical use cases for modifying enqueued scripts:

Modifying jQuery Scripts

jQuery scripts can modify behavior sitewide. For example, to log all Ajax requests:

function filter_jquery($tag, $handle){

    if('jquery-core' == $handle){
        $tag = str_replace('jquery.min.js','custom-jquery.js', $tag); 
    }

    return $tag;

}
add_filter('script_loader_tag', 'filter_jquery', 10, 2);

function custom_jquery(){
  wp_enqueue_script('jquery-core', '//code.jquery.com/jquery-3.6.0.min.js');

  $custom = file_get_contents(ABSPATH . 'wp-includes/js/jquery/jquery.js');

  $custom = preg_replace('/jQuery.ajax(?={)/', 'console.log("Ajax called"); jQuery.ajax', $custom );

  wp_add_inline_script('jquery-core', $custom);  
}

add_action('wp_enqueue_scripts', 'custom_jquery');

Combining Multiple Scripts

Reduce HTTP requests by combining similar scripts:

function concat_widget_scripts(){

    global $wp_scripts;

    $js1 = $wp_scripts->registered['widget-script1']->src;
    $js2 = $wp_scripts->registered['widget-script2']->src;

    $combined_source = file_get_contents($js1) . ';' . file_get_contents($js2);

    wp_register_script('new-widget-script', false);
    wp_enqueue_script('new-widget-script', false, array('jquery'), '1.0', true);
    wp_add_inline_script('new-widget-script', $combined_source);

}  
add_action('wp_enqueue_scripts','concat_widget_scripts');

Forcing Script Reload

Force browser and cache refresh of a problem script:

function enqueue_new_script(){

  $ver = date('mdY'); //new version 

  wp_enqueue_script('problematic-script', 'path/to/script.js', array(), $ver);

}
add_action('wp_enqueue_scripts', 'enqueue_new_script'); 

Can help fix issues with outdated script versions loading.

Additional Tips and Considerations

Some other tips when modifying enqueued scripts:

Plugin Compatibility Issues

Changes to plugin-enqueued scripts can sometimes cause problems. Test any modified plugins scripts carefully.

Script Debugging

Debug JavaScript errors with browser dev tools or the console.log() function.

Handling Caching Issues

Forcibly refreshing scripts with version increments often fixes stale caching problems.

CDNs and caching plugins can also complicate updates – modifying headers/expiration may help.

Leave a Reply

Your email address will not be published. Required fields are marked *