Recently I was wondering how to dynamically load phonegap.js per mobile platform. I mean, when using PhoneGap Build, you could just add
to the <head/> of your page, but what about running your app outside PhoneGap Build in a Simulator, on your device, or even as a website locally on your laptop?
Dynamically load phonegap.js per mobile platform
Ofcourse there are more ways to solve the problem, but what we did was really easy and working extremely well: we load our own phonegap/cordova.js file based on the useragent while loading the page and don’t include it in the head at all. Your app supports all deployment scenario’s, even on PhoneGap Build.
Add this to any .js file every page of your webapp needs Cordova functionality for. We’ve included it in a core.js file, which is included in the head of every page. Note that this app doesn’t use jQuery, but Vanilla.js, the fastest JS framework on the planet.
Let me explain the highlighted lines:
Lines 5 & 7: Determine the platform by querying the useragent, nothing fancy, so didn’t include details.
Line 12: The correct version for your platform is loaded. By using document.write the library gets evaluated immediately and that’s what we want!
Line 19: Don’t wait for ‘document ready’ or similar events, we want the js evaluated right away.