如何将我的javascript放在页脚中

问题描述 投票:0回答:5

我只是想问如何使用简单的插件在页脚打印脚本“javascript”。我正在使用 WordPress 3.0 有什么想法吗?

javascript wordpress plugins
5个回答
113
投票

在主题模板中使用functions.php文件添加以下内容:

<?php

function add_this_script_footer(){ ?>

[YOUR JS CODE HERE]

<?php } 

add_action('wp_footer', 'add_this_script_footer'); ?>

42
投票

对于要在页脚中链接的外部 javascript 文件,请使用此文件 (>= WP2.8)

function my_javascripts() {
    wp_enqueue_script( 'the-script-handle', 
                       'path/to/file.js', 
                       array( 'jquery','other_script_that_we_depend_on' ), 
                       'scriptversion eg. 1.0', 
                       true);
}
add_action( 'wp_enqueue_scripts', 'my_javascripts' );

最后一个 true 意味着脚本应该放在 wp_footer() 钩子上。


13
投票

嗯,现在回答可能已经太晚了,但如果其他人也遇到同样的问题:

有一个插件可以做到这一点: http://wordpress.org/extend/plugins/footer-javascript/

或者您可以通过在functions.php中添加这个简短的代码来手动执行此操作:

/**
 * Automatically move JavaScript code to page footer, speeding up page loading time.
 */
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_head_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_head_scripts', 5);

7
投票

在主题(或子主题,如果存在)模板中使用functions.php文件添加以下内容:

function add_this_script_footer() { 
?>
<script>
`enter code here`
</script>
<?php } 
add_action('wp_footer', 'add_this_script_footer');

0
投票

您可以在父主题或子主题中使用 function.php(如果存在)

<?php function add_this_script_footer() { ?> 
// Paste your entire script here 
<?php } 
add_action('wp_footer', 'add_this_script_footer');

对于外部脚本使用这个

function enqueue_external_js_in_footer() {
    wp_enqueue_script(
        'external-js', // Handle
        'https://example.com/external-script.js', // External script URL
        array(), // Dependencies
        null, // Version
        true // Set true to load in the footer
    );
}
add_action('wp_enqueue_scripts', 'enqueue_external_js_in_footer');

使用异步加载

function add_async_attribute($tag, $handle) {
    if ( 'your-handle-name' !== $handle ) {
        return $tag;
    }
    return str_replace( ' src', ' async="async" src', $tag );
}
add_filter('script_loader_tag', 'add_async_attribute', 10, 2);
© www.soinside.com 2019 - 2024. All rights reserved.