Manually bootstrapping AngularJS for asynchronous loading in Internet Explorer
AngularJS is well known for its magical DOM bindings, and that extends to the way it gets initialised. By default the trigger for loading an Angular application is to include an ng-app
attribute on the <html>
element of your document. Something along the lines of:
<html ng-app="myApp">
Angular reads the value from this attribute and sets itself up to boot when the DOMContentLoaded
event fires. In most modern browsers, this works as expected regardless of how you’re loading your JavaScript, but in older versions of Internet Explorer it fails if you’re loading your JavaScript assets asynchronously (and you should be). Using Modernizr’s .load()
method sees Angular initialising itself before you’ve had a a chance to set the app up, which means all you controllers will end up appearing as undefined
functions in <IE8.
Thankfully, there’s an easy way to get around this. Angular lets you explicitly bootstrap your app through JavaScript rather than relying on the magic initialisation:
angular.element(document).ready(function() {
angular.bootstrap(document, ["myApp"]);
});
Angular includes a ‘lite’ flavour of jQuery, so you can use the standard jQuery .ready()
syntax to ensure the bootstrap function is called after both your app has loaded and the DOM is ready for manipulation. It’s important to use .ready()
as it ensures the function will be called even if your JavaScript loads after the DomContentLoaded
event has fired.