最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a way to check for an attribute of a script when using script_loader_tag?

programmeradmin2浏览0评论

The block of code adds the attribute async to a array of Javascript files.

Is there a way to check if the files have already have the attribute assigned and if yes, to skip it?

function async_scripts( $tag, $handler, $src ) {
    
    /**
     * An array of JavaScripts files. The value should be the filename.
     */
    $scripts = array(
        'script_one.js',
        'script_two.js'
    );
    
    /**
     * Loop through each file in the $scripts array and add an async option.
     */
    foreach ( $scripts as $script ) {

        if ( true == strpos( $tag, $script ) )
        return str_replace( ' src', ' async src', $tag );
    }

    return $tag;

}
add_filter( 'script_loader_tag', 'async_scripts', 10, 3 );

I tried looping through global $wp_scripts however it doesn't appear to work with script_loader_tag

foreach( $wp_scripts->registered as $script ) {
            if ( ! empty( $script->extra['async'] ) && $script->extra['async'] === true ) {
                return $tag;
            }
发布评论

评论列表(0)

  1. 暂无评论