【问题标题】:How to enqueue jQuery asynchronously in wordpress?如何在wordpress中异步排队jQuery?
【发布时间】:2018-05-11 09:30:57
【问题描述】:

我的主题使用捆绑的 jQuery 的 Wordpress,我想异步加载它。 (是的,PageSpeed Insights...)

【问题讨论】:

    标签: javascript php wordpress


    【解决方案1】:

    script_loader_tag 有一个钩子。你可以像下面这样使用它

    add_filter( 'script_loader_tag', 'add_async_to_script', 10, 3 );
     
    function add_async_to_script( $tag, $handle, $src ) {
    
        //You can use this to make all async
    
        $tag = str_replace( ' src', ' async src', $tag );
    
        // You can use this to make it work as below for a specific script
    
        if ( 'dropbox.js' === $handle ) {
            $tag = '<script async type="text/javascript" src="' . esc_url( $src ) . '"></script>';
        }
     
        return $tag;
    }
    

    【讨论】:

    • 谢谢,它有效!不幸的是,如果我异步加载脚本,PageSpeed 并没有给我更多的分数。 :/ 我试着推迟它。
    【解决方案2】:

    根据您网站的功能,异步延迟或加载 jquery 可能会影响页面的加载方式,甚至会破坏功能。也可以顺利运行。

    但为了给你一个正确的答案,我必须建议你不要这样做。

    如果你还想尝试,这里有一些参考

    https://wpshout.com/make-site-faster-async-deferred-javascript-introducing-script_loader_tag/

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 2016-08-24
      • 1970-01-01
      相关资源
      最近更新 更多