andershagbard
andershagbard

Reputation: 1137

Require.js - jQuery + jQuery dependent file (Wait untill file ready)

I have some problems with require.

require.config({
    paths: {
        "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min"
    },
    waitSeconds: 40
});


requirejs(['jquery', '//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.2/owl.carousel.min.js'], function(jQuery){
    $(function() {
        $('#carousel').owlCarousel({
            singleItem: true,
            autoPlay: true,
            stopOnHover: true,
            lazyLoad: true,
            itemsScaleUp: true
        });
    });
});

This only works every 2nd time i load the page (cache?)

I think i need to load my owl.carousel.js script, after jQuery is ready, but how?

Upvotes: 2

Views: 1619

Answers (2)

karantan
karantan

Reputation: 1015

You have to wrap the lib inside define function like this:

define(['jquery'], function( jQuery ) {
...
// OwlCarousel code
...
});

Some libs have implemented "AMD support" so you don't have to do this. You can check this by ctrl+f "amd" and see if the lib contains this string.

Upvotes: -1

Evan
Evan

Reputation: 6115

You can set dependencies in the shim:

require.config({
    paths: {
        "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min",
        "owl" : "//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.2/owl.carousel.min.js"
    },
    waitSeconds: 40,
     shim: {
            'owl': {
                //These script dependencies should be loaded before loading
                // owl
                deps: ['jquery']
            }
        }
});

If this doesn't work, I would recommend downloading the files for jquery and owl and placing them in your local directory because Require can be annoying with loading files from CDNs.

Upvotes: 5

Related Questions