Search code examples
javascriptrequirejsamdscrollmagic

Using ScrollMagic.js as AMD module


How can one use the excellent ScrollMagic JS plugin as an AMD module to use with requirejs for example?

I couldn't find any reference to that online and looking at the code of ScrollMagic it doesn't seem as if it loads as an AMD module.

It does define 2 variables in the window level at the end of the module:

window.ScrollScene = ScrollScene;
window.ScrollMagic = ScrollMagic;

so it seems that a simple shim won't do because I'll need to export two variables. Is there a way to export that?

Any ideas?

Thanks!


Solution

  • I found something that works for me, it's little bit of a work around, but it does the trick.

    in the shim configuration of requirejs I use:

    shim: {
        'scrollmagic': {
            deps:['jquery', 'TweenMax'], 
            exports: 'ScrollMagic', 
            init: function() {
                return {ScrollMagic: ScrollMagic, 
                        ScrollScene: ScrollScene};
            }
        }
    }
    

    This is to comply with the fact that ScrollMagic requires jQuery as well as GSAP TweenMax libraries to be loaded.

    It turns out that using the init function of the shim and then returning the two variables, does the trick.

    BUT - this means that for using the ScrollMagic plugin one should use (example):

    define(['scrollmagic'], function(scrollmagic) {
        var magic = new scrollmagic.ScrollMagic();
        var scene = new scrollmagic.ScrollScene({duration: 200});
    });
    

    Hoping that this will help somebody in the future...

    == Edit ==

    ScrollMagic 1.3 now supports the AMD pattern, so all this is unnecessary.