RequireJS and its asynchronous quirks

Veröffentlicht: 14. Mai 2014 in Web
Schlagwörter:, , , , , ,

For a current project I use RequireJS with Backbone and Handelbars to create some fancy single page web application😉 After playing around and getting everything togethet, I noticed some strange and randomly occurring errors.

My setup looks like this:

| js/
  | app/
    - [...]
    - main.js
    - config.js
  | libs/
    - [...]
    - require.js

The main.js wires RequireJS and starts up the application. Here is an excerpt from main.js file:

require.config({
    deps: ['config']
});

require(['dummy/app', 'jquery', 'jqueryui', 'underscore', 'backbone'], function (App) {
    new App();
});

I exported the RequireJS configuration into its own file (config.js), because I needed almost the same configuration for unit testing the application via karma. Here is an excerpt from config.js file:

require.config({
    paths: ...
    shim: ...
});

Sometimes the app tried to load my libraries from paths like „js/app/jquery.js„, but the libraries were located under „js/libs/…„!
After googling around I noticed that RequireJS is loading every content asynchronously by adding „async“ as attribute to the <script> tag. The same behavior occurs for loading external RequireJS configuration files. The following statement loads its sub-configutation also async!

require.config({
    deps: ['config']
});

After becoming aware of this feature, I wrapped the initialization of the main application into another require(..) statement (as described on stackoverflow.com). The loading process and linking of external asynchronously loaded content was now fixed.

Here is an excerpt of the fixed main.js file:

require.config({
    deps: ['config']
});

require(['config'], function () {
    require(['dummy/app', 'jquery', 'jqueryui', 'underscore', 'backbone'], function (App) {
        new App();
    });
});

Schreibe einen Kommentar

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s