加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > CMS系统 > wordpress > 正文

wordpress把JavaScript files 移动到HTML文档底部

发布时间:2020-12-14 14:35:07 所属栏目:wordpress 来源:网络整理
导读:为了提高你的WordPress博客的加载速度,建议您将JavaScript文件移动到HTML文档底部。但是,很多插件在必须加装在文档的头部,我们强制移动底部,会出现插件失效,这是一个简单的解决方案来自动将所有JavaScript文件移动到文档的底部,从而提高网页的加载速度

为了提高你的WordPress博客的加载速度,建议您将JavaScript文件移动到HTML文档底部。但是,很多插件在必须加装在文档的头部,我们强制移动底部,会出现插件失效,这是一个简单的解决方案来自动将所有JavaScript文件移动到文档的底部,从而提高网页的加载速度,如果你在进行wp主题的开发,这对你的主题加载效率有很大帮助。

首页,把以下代码复制到 functions.php文件中

/**

* Filter HTML code and leave allowed/disallowed tags only

*

* @param string $text Input HTML code.

* @param string $tags Filtered tags.

* @param bool $invert Define whether should leave or remove tags.

* @return string Filtered tags

*/

function theme_strip_tags_content($text,$tags = '',$invert = false) {

preg_match_all( '//si',trim( $tags ),$tags );

$tags = array_unique( $tags[1] );

if ( is_array( $tags ) AND count( $tags ) > 0 ) {

if ( false == $invert ) {

return preg_replace( '@.*?@si','',$text );

}

else {

return preg_replace( '@.*?@si',$text );

}

}

elseif ( false == $invert ) {

return preg_replace( '@.*?@si',$text );

}

return $text;

}

/**

* Generate script tags from given source code

*

* @param string $source HTML code.

* @return string Filtered HTML code with script tags only

*/

function theme_insert_js($source) {

$out = '';

$fragment = new DOMDocument();

$fragment->loadHTML( $source );

$xp = new DOMXPath( $fragment );

$result = $xp->query( '//script' );

$scripts = array();

$scripts_src = array();

foreach ( $result as $key => $el ) {

$src = $result->item( $key )->attributes->getNamedItem( 'src' )->value;

if ( ! empty( $src ) ) {

$scripts_src[] = $src;

} else {

$type = $result->item( $key )->attributes->getNamedItem( 'type' )->value;

if ( empty( $type ) ) {

$type = 'text/javascript';

}

$scripts[$type][] = $el->nodeValue;

}

}

//used by inline code and rich snippets type like application/ld+json

foreach ( $scripts as $key => $value ) {

$out .= '';

}

//external script

foreach ( $scripts_src as $value ) {

$out .= '';

}

return $out;

}

其次 编辑 header.php 文件, 移除 wp_head()函数

ob_start();

wp_head();

$themeHead = ob_get_contents();

ob_end_clean();

define( 'HEAD_CONTENT',$themeHead );

?

$allowedTags = '

print theme_strip_tags_content( HEAD_CONTENT,$allowedTags );

?>

最后把以下代码放到 footer.php 文件的

有关wordpress加载Js,建议阅读:WordPress引入css/js两种方法


原文阅读:http://www.wprecipes.com/wordpress-tip-move-all-javascript-files-to-the-footer-automatically

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读