我在 WordPress 网站的主页上有一个基于 jquery 的自定义 slider 。我在主题的 functions.php 文件中使用以下代码加载 jQuery (jquery.js) 和 slider js (jquery.advanced-slider.js)。
function my_load_scripts() {
if (!is_admin()) {
wp_enqueue_script("jquery");
if (is_home()) {
wp_enqueue_script('theme-advanced-slider', get_template_directory_uri().'/js/jquery.advanced-slider.js', array('jquery'));
wp_enqueue_script('theme-innerfade', get_template_directory_uri().'/js/innerfade.js', array('jquery'));
}
}
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
现在我在 wp_head() 之前将下面的代码放在我的 header.php 文件中;
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function () {
//Slider init JS
$j(".advanced-slider").advancedSlider({
width: 614,
height: 297,
delay: 1000,
pauseRollOver: true
});
});
</script>
很明显,我的 jquery.js 和 jquery.advanced-slider.js 在上面的 JavaScript 代码之后加载,因此我的 slider 不起作用。如果我把它放在 wp_head() 调用 <head>
之后 slider 有效。
但是如果我把它放在 wp_head() 之后,那岂不是很乱?我希望我的代码干净。正如 twentyeleven theme 明确指出的那样
/* Always have wp_head() just before the closing </head>
* tag of your theme, or you will break many plugins, which
* generally use this hook to add elements to <head> such
* as styles, scripts, and meta tags.
*/
我在这里很困惑。我可能在这里遗漏了一些非常简单的线索。但是请帮帮我。将 JavaScript 放在 wp_head() 之前并在加载 jquery.js 和 slider.js 之后加载它的最佳方法是什么?
最佳答案
将您的脚本 block 添加到 HTML 页面的底部,就在 </body>
之前.
在浏览器中解析完整的 DOM 之前,您的 slider 初始化 JS 代码不会被执行,因此这没有缺点。
事实上像 Steve Souders 这样的网络性能专家 suggest that script blocks should be added at the end of your HTML page因为脚本会阻止呈现,并且页面似乎以这种方式加载得更快。
关于javascript - 在 WordPress 站点中加载 jquery.js 后加载 javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12225664/