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

前端之家收集整理的这篇文章主要介绍了wordpress把JavaScript files 移动到HTML文档底部前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

为了提高你的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()函数

PHP

ob_start();

wp_head();

$themeHead = ob_get_contents();

ob_end_clean();

define( 'HEAD_CONTENT',$themeHead );

 

$allowedTags = 'Meta>

print theme_strip_tags_content( HEAD_CONTENT,$allowedTags );

?>

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

PHP theme_insert_js( HEAD_CONTENT ); ?>

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


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

原文链接:https://www.f2er.com/wordpress/422839.html

猜你在找的wordpress相关文章