Posts

Configure RequireJS to load the yalst live chat JavaScript Api

TL;DR

For loading outdated versions of the Visitor Chat JavaScript Api ensure the release version of RequireJS does finish loading it’s data-main script before fetching the Visitor Api.

Update – this post’s solution is now obsolete (1. Aug. 2014)

The co-existence problems of the two RequireJS libraries have been resolved with the version 2.1 of the VisitorAPI. The VisitorAPI library is distributed from now on as a single JavaScript file too. That source file is AMD loader compatible. Thus the VisitorAPI v. 2.1 no longer introduces global variables in the JavaScript context.

The whole loading code condenses down to:

The details are discussed in this tutorial.

The Original Problem

The RequireJS library adds support for Javascript modules which is missing in the current webbrowser implementations.
The yalst Visitor Api uses a renamed RequireJS (version 2.1.9 at the time of writing) for code organisation and loading, and so may the client pages themselves.
However since RequireJS does not provide a noConflict() method both versions can interfere on the page resulting in Javascript errors.

RequireJS in the Visitor Api

The Visitor Chat JavaScript Api provides the namespace LiveSupport which

  • under the namespace LiveSupport.VisitorAPI contains the documented public methods and
  • under the root contains it’s own version of RequireJS.

Thus in addition to the documented use these methods are available in the Api too:

The api is put in this namespace by the RequireJS optimiser r.js using a build.js file like this:

The Solution

The client page can use it’s own (non-namespaced) version of RequireJS, given it completes loading the data-main script before the Visitor Api’s namespaced version.

An Example

The example page index-sync.html uses RequireJS in require.min.js with the data-main script main.js to load jQuery, underscore and Lo-Dash.
In this example the <script> tag for the Visitor Api is created “by hand” [1] in a function called from the data-main script main.js. This tag loads the Visitor Api’s own namespaced RequireJS in LiveSupport.js with the data-main script LiveSupportMain.js which in turn loads the actual api source files.
Among the api files is yet an own version of underscore which by using _.noConflict() is guaranteed to be free of side effects for the client page.

The directory structure and the network activity log of a web page containing both the vanilla version of RequireJS and the namespaced version of the Visitor Api is shown here:
RequireJS NoConflict Loading NetworkLog
Here is the code to accomplish sequential loading of the libraries:

[1] To define the order in which the libraries are fetched by the browser loadScript.js could be used for dynamic injection of <script> tags into the DOM and handling of the load and readystatechange events.