简体   繁体   English

在页脚中调用jQuery函数或在wordpress中加入函数是否更容易接受?

[英]Is it more acceptable to call jQuery functions in the footer or enqueue in functions in wordpress?

Massive hat tip to the community, here, you folks are my go-to most days! 大量的帽子提示给社区,在这里,你们是我最喜欢的日子!

I think my topic says it all, really, with relation to jQuery in WordPress - I've been thinking a lot lately that placing jQuery commands in functions.php would make the effects happen sooner rather than in placing them in footer.php which would be a good thing, I think. 我认为我的主题确实说明了与WordPress中的jQuery有关的全部内容-最近我一直在思考,将jQuery命令放在functions.php中将使效果更早发生,而不是将它们放在footer.php中。我认为这是一件好事。 Can anyone see any flaws with this approach? 有人可以看到这种方法有什么缺陷吗?

-Jc -Jc

This question is primarily opinion based. 这个问题主要基于意见。 However, the proper way to include JavaScript files in WordPress is to properly "enqueue" them using the wp_enqueue_script() function, from the 'wp_enqueue_scripts' action hook. 但是,在WordPress中包含JavaScript文件的正确方法是使用'wp_enqueue_scripts'操作钩子中的wp_enqueue_script()函数适当地“入队”它们。

To speed up page load, many people prefer to enqueue scripts in the footer, using the 4th and final parameter of wp_enqueue_script() . 为了加快页面加载速度,许多人都喜欢使用wp_enqueue_script()的第4个也是最后一个参数将脚本排入页脚。

Doing the following will ensure that your script is properly enqueued, that it's dependencies have been satisfied, and that it's in the footer (added via wp_footer() ): 执行以下操作将确保脚本正确入队,满足了其依赖关系,并且位于页脚(通​​过wp_footer()添加)中:

/**
 * Proper way to enqueue a script with a jQuery dependency, in the footer
 */
function theme_name_scripts() {
    wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' );

For more reasons about why you should use this function instead of hard-coding them into the footer of your theme, check out this post on WPSE . 有关为什么您应该使用此功能而不是将其硬编码到主题页脚中的更多原因,请查看WPSE上的这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM