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

首页,把以下代码复制到 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( '/<(.+?)[\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.*?>.*?@si', '', $text );
        }
        else {
            return preg_replace( '@<('. implode( '|', $tags ) .')\b.*?>.*?@si', '', $text );
        }
    }
    elseif ( false == $invert ) {
        return preg_replace( '@<(\w+)\b.*?>.*?@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 = '<style><link><meta><title>';
print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );
?>

最后把以下代码放到 footer.php 文件的 </body> 前

<?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


发布日期:

所属分类: Wordpress 综合 标签:


没有相关文章!