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()函数ob_start(); wp_head(); $themeHead = ob_get_contents(); ob_end_clean(); define( 'HEAD_CONTENT',$themeHead ); ? $allowedTags = ' |