How can I remove the site URL from enqueued scripts and styles?

Similar to Wyck’s answer, but using str_replace instead of regex.

script_loader_src and style_loader_src are the hooks you want.

<?php
add_filter( 'script_loader_src', 'wpse47206_src' );
add_filter( 'style_loader_src', 'wpse47206_src' );
function wpse47206_src( $url )
{
    if( is_admin() ) return $url;
    return str_replace( site_url(), '', $url );
}

You could also start the script/style URLs with a double slash // (a “network path reference“). Which might be safer (?): still has the full path, but uses the scheme/protocol of the current page.

<?php
add_filter( 'script_loader_src', 'wpse47206_src' );
add_filter( 'style_loader_src', 'wpse47206_src' );
function wpse47206_src( $url )
{
    if( is_admin() ) return $url;
    // why pass by reference on count? last arg
    return str_replace( array( 'http:', 'https:' ), '', $url, $c=1 );
}

Leave a Comment

tech