Clean-up script tags

I want to clean up <script> tags generated by WordPress to produce more semantic output for HTML5.

You can already do this for <style> tags using this code attached to the style_loader_tag filter:

Read More
//clean up the default WordPress style tags
add_filter('style_loader_tag', 'clean_style_tag');

function clean_style_tag($input) {
    preg_match_all("!<link rel='stylesheet's?(id='[^']+')?s+href='(.*)' type='text/css' media='(.*)' />!", $input, $matches);

    //only display media if it's print
    $media = $matches[3][0] === 'print' ? ' media="print"' : '';                                                                             
    return '<link rel="stylesheet" href="' . $matches[2][0] . '"' . $media . '>' . "n";
}

But there isn’t an equivalent script_loader_tag in core yet. It was proposed in the past, but for now we need a workaround.

I’ve started looking in /wp-includes/class.wp-scripts.php at function do_item( $handle, $group = false ) around line 79 which holds the script output (specifically lines 117-120), but I’m having a bit of trouble finding an appropriate filter that could be used here.

Related posts

Leave a Reply

2 comments

  1. If you really want to do this, then it should already be possible.

    The global $wp_scripts is an instance of the WP_Scripts class, which is an instance of the WP_Dependencies class.

    So in theory (not tested), you should be able to do something like this:

    function alter_script_tags()
    {
        echo '<pre>';
            print $GLOBALS['wp_scripts']->print_html;
        echo '</pre>';
    }
    add_action( 'wp_enqueue_scripts', 'alter_script_tags', 999999 );
    

    This is just a rough sketch, but you should get the idea.

  2. Unsure of WP version compatibility, but taken from the Soil plugin module clean-up.php for Roots. Use in your theme’s functions.php or similar.

    function clean_script_tag($input) {
      $input = str_replace("type='text/javascript' ", '', $input);
      return str_replace("'", '"', $input);
    }
    add_filter('script_loader_tag', 'clean_script_tag');