Angular 4 + Cordova + Device Ready

Viewed 6181

What is the best approach to run (or bootstrapping) an angular-cli based app on Cordova?

Note: This is for an Angular 4.x app for which multiple Cordova plugins are being used.

Option A: Post ng build, in your www/index.html (www is Cordova folder) should you do something like:

<script src="cordova.js"></script>
<script>
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
  console.log('onDeviceReady has been called. Lets start loading JS files.');
  var url = ['inline.bundle.js', 'polyfills.bundle.js', 'styles.bundle.js', 'vendor.bundle.js', 'main.bundle.js'];
  for(var i = 0; i < url.length; i++){
    loadJSFile(url[i]);
  }
}

function loadJSFile(url) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    head.appendChild(script);
}
</script>

OR,

Option B: The onDeviceReady() can go somewhere inside main.ts (before bootstrapping AppModule), or app.component.ts.

I have tried Option A, but my app is taking too long to load on iPad. So I wanted to know if I am following a good approach or not. Thanks in advance for your suggestions.

3 Answers

If you need to add a check for Cordova as well, you need more complex code. Otherwise Angular will complain about 'Tried to find bootstrap code, but could not. Specify either statically analyzable bootstrap code or pass in an entryModule to the plugins options.'

const bootstrap = () => {
  platformBrowserDynamic().bootstrapModule(AppModule);
};

if (typeof window['cordova'] !== 'undefined') {
  document.addEventListener('deviceready', () => {
    bootstrap();
  }, false);
} else {
  bootstrap();
}

In main.ts or main-aot.ts depends how you call your main.ts file

 document.addEventListener('deviceready', () => {
    console.log("bootstrap device");
    platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
  }, false);
}
Related