在 WordPress 站点中加载 jquery.js 后加载 javascript 代码

2024-01-25

我在 WordPress 网站的主页上有一个基于 jquery 的自定义滑块。我正在主题的functions.php 文件中使用以下代码加载jQuery (jquery.js) 和滑块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');

现在我将以下代码放入 header.php 文件中,然后放在 wp_head(); 之前

<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 代码之后加载,因此我的滑块不起作用。如果我把它放在 wp_head() 调用之后<head>滑块可以工作。

但如果我把它放在 wp_head() 之后,那不是黑客吗?我希望我的代码是干净的。正如二十一主题明确指出的那样

/* 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 加载后加载它的最佳方法是什么?


将脚本块添加到 HTML 页面的底部,就在</body>.

无论如何,在浏览器中解析完整的 DOM 之前,滑块初始化 JS 代码不会被执行,因此这没有任何缺点。

事实上,像 Steve Souders 这样的 Web 性能专家建议在 HTML 页面末尾添加脚本块 http://www.stevesouders.com/blog/2009/05/06/positioning-inline-scripts/因为脚本会阻止渲染,因此页面加载速度似乎会更快。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 WordPress 站点中加载 jquery.js 后加载 javascript 代码 的相关文章

随机推荐