WordPress程序确实上手比较容易,但是后续如果需要完美的兼容和稳定还是需要不断的调整的。比如我们安装各种插件和主题之后,会看到源代码顶部有很多的JS文件,一来会使得网站打开速度变慢,二来还会影响网站的用户体验,我们需要做的最好是将JavaScript文件减少或者是移动到网站底部。

这里老蒋整理到一个不错的办法,可以将所有的WordPress程序中的JavaScript文件移动到网站底部。具体如何操作呢?

第一、添加脚本

> function theme_strip_tags_content($text, $tags = '', $invert = false) {
> preg_match_all( '/<(.+?)[\s]\/?[\s]>/si', trim( $tags ), $tags );
> $tags = array_unique( $tags[1] );
> if ( is_array( $tags ) AND count( $tags ) > 0 ) {
> if ( false == $invert ) {
> return preg_replace( '@<(?!(?:'. implode( '|', $tags ) .')\b)(\w+)\b.?>.?</\1>@si', '', $text );
> }
> else {
> return preg_replace( '@<('. implode( '|', $tags ) .')\b.?>.?</\1>@si', '', $text );
> }
> }
> elseif ( false == $invert ) {
> return preg_replace( '@<(\w+)\b.?>.?</\1>@si', '', $text );
> }
> return $text;
> }
> 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;
> }
> }
> foreach ( $scripts as $key => $value ) {
> $out .= '<script type="'.$key.'">';
> foreach ( $value as $keyC => $valueC ) {
> $out .= "\n".$valueC;
> }
> $out .= '</script>';
> }
> foreach ( $scripts_src as $value ) {
> $out .= '<script src="'.$value.'"></script>';
> }
> return $out;
> }

将代码添加到当前主题的Functions.php文件中。

第二、替换头部文件

> <?php
> ob_start();
> wp_head();
> $themeHead = ob_get_contents();
> ob_end_clean();
> define( 'HEAD_CONTENT', $themeHead );
> $allowedTags = '<style><link><meta><title>';
> print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );
> ?>

将当前主题的wp_head()头部文件这个代码替换到上面脚本。

第三、增加底部文件

> <?php theme_insert_js( HEAD_CONTENT ); ?>

在footer.php底部文件中加上上面的代码。

最后,我们刷新当前的WP网站,可以看到所有的JS文件已经在网站底部。