Louis Louis - 1 month ago 15
AngularJS Question

Intermittent "Looking up elements via selectors is not supported by jqLite!" when loading AngularJS with RequireJS

I load AngularJS through RequireJS. Most of the time there is no problem but once in a while I get the error:


Uncaught Error: [jqLite:nosel] Looking up elements via selectors is not supported by jqLite!


I know that everything is actually loading so the issue is not with RequireJS not finding the files.

Here is my RequireJS configuration:

require.config({
baseUrl: 'lib/',
paths: {
jquery: 'external/jquery-2.1.1',
angular: 'external/angular',
},
shim: {
angular: {
exports: "angular"
},
},
});


Here is how I load RequireJS and kickstart the load:

<script type="text/javascript" src="lib/requirejs/require.js"></script>
<script type="text/javascript" src="requirejs-config.js"></script>
<script>
require(["start"]);
</script>


I'm using AngularJS 1.3.0 and RequireJS 2.1.15.

Answer

Intermittent problems like this are usually due to a missing dependency somewhere. Most of the time your modules load in the correct order but that's just due to chance. Once in a while, luck is not on your side and you get undesirable results.

The issue is that AngularJS uses jQuery only optionally. If it is present, then AngularJS uses it. If it is absent, then AngularJS will use a jqLite library, bundled with AngularJS, that supports a subset of what jQuery can do. One important difference is that a statement like:

angular.element('[ng-controller="something"]')

will work only if jQuery is available to AngularJS, and won't work if jqLite is used instead. If RequireJS loads AngularJS before jQuery, then AngularJS will be working without jQuery and the statement will fail.

This can be fixed by changing your AngularJS shim to:

 shim: {
   angular: {
       deps: ['jquery'],
       exports: "angular"
   },
 },
Comments