Tutorial: Loading as RequireJS module

Loading as RequireJS module

The RequireJS module loader is a de facto standard for using JavaScript modules in pre ECMA-6 browsers.

1.) Load the RequireJS module loader

<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.9/require.min.js"
          async
          data-main="data-main.js"></script>

2.) Set the path in the RequireJS configuration.

E.g. in the data-main JS file

requirejs.config({
    paths: {
            /// load the Visitor API from the module named "LiveSupport"
            LiveSupport: '//YALST_PRODUCT_SERVER/YALST_DIRECTORY/visitor_api/v2.1/LiveSupport.min',

            /// or alternatively load the anonymous module
            yalstAPI: '//YALST_PRODUCT_SERVER/YALST_DIRECTORY/visitor_api/v2.1/LiveSupportAnonymous.min'
        }
    }
);

3.) In a two-step mechanism load the library at will

require(["LiveSupport"], function(LiveSupportLibrary)
    {
        LiveSupportLibrary.require(["api/VisitorAPI"], function(api)
            {
                // use the VisitorAPI provided in the api argument

            }
        );
    }
);

Note that there are no variables introduced into the global JavaScript context.