RequireJS 偶发性故障

RequireJS sporadic failure

我正在 Magento2 网站上工作。 Magento2 使用 requirejs,我正在使用的主题也使用了它。部分主题使用Owl Carousel。用来加载轮播的代码原来是

require(['jquery', 'owl.carousel/owl.carousel.min'], function($) {
    $("#banner-slider-demo-1").owlCarousel({
        // carousel settings
    });
});

但是我注意到有时当我加载主页(使用轮播的地方)时轮播不显示,并且控制台中有错误

Uncaught TypeError: $(...).owlCarousel is not a function

想到jQuery可能加载不出来,改了require code序列化需求

require(['jquery'], function($) {
    require(['owl.carousel/owl.carousel.min'], function () {
        $("#banner-slider-demo-1").owlCarousel({
            // ...

但这没有效果...有时轮播加载并且没有错误,其他时候有错误并且没有加载。

即使出现错误,轮播文件也已被浏览器提取。似乎还需要根据开发人员工具加载轮播脚本

知道会发生什么吗?

您的问题是您正在通过 script 元素 通过 RequireJS 加载 jQuery。您必须使用一种方法,不能同时使用两种方法。

如果我在控制台中运行这个:

console.log("owlCarousel", typeof jQuery.fn.owlCarousel)

我得到:

owlCarousel function

但是有了这个:

require(["jquery"], function ($) { 
  console.log("owlCarousel", typeof $.fn.owlCarousel); 
})

我得到:

owlCarousel undefined

如果你尝试 require(["jquery"], function ($) { console.log("equal", $ === window.jQuery); }),你会得到 equal false。因此,您加载了两个 jQuery 实例。使用 RequireJS 访问 jQuery 的代码得到一个没有 .owlCarousel 的版本。那是因为 Owl Carousel 安装在 window.jQuery.

如果由于某种原因必须通过 script 加载 jQuery,则应在加载 之前移动加载它的 script 元素 需要JS。 (你应该为你加载的 所有 脚本执行此操作,你想用 script 加载它们是 AMD 感知的。)然后对于 RequireJS,你应该只定义这个假模块:

define("jquery", function () {
    return jQuery;
});

这使得当 RequireJS 加载 jQuery 时,它只使用已经在全局 space 中定义的 jQuery。这个假模块的理想位置是在您配置 RequireJS 之前。

当你在做的时候,你应该为 owl.carousel/owl.carousel.min:

定义一个 shim
`owl.carousel/owl.carousel.min`: ['jquery']

这样就不需要将加载 owl.carousel/owl.carousel.min 的调用嵌套在加载 jquery 的调用中。你可以只做你最初尝试的事情:

require(['jquery', 'owl.carousel/owl.carousel.min'], function($) {
  $("#banner-slider-demo-1").owlCarousel({
    // carousel settings
  });
});