Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 + Cordova + Device Ready

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.

like image 786
hmadev Avatar asked Jun 29 '17 13:06

hmadev


2 Answers

I don't know if this is the best approach but in my main.ts I added the deviceready event listener with an arrow function which calls the angular bootstrap. It works.

document.addEventListener("deviceready", () => platformBrowserDynamic().bootstrapModule(AppModule), false);

like image 166
Gergő Kajtár Avatar answered Oct 21 '22 18:10

Gergő Kajtár


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();
}
like image 32
Niels Steenbeek Avatar answered Oct 21 '22 18:10

Niels Steenbeek