I figured this was a common scenario and was surprised not to find an answer here. So here it goes…
Some pages within my jquerymobile site are using external javascripts. I don’t want these scripts to load on every page on the site. It’s mobile and it should load fast.
How can I load the external javascript so it is available in the DOM when it needs to be referenced. I found this Stack article which seems to have a good technique: Using Javascript to load other external Javascripts
If I dynamically load this external javascript, should I use the pageinit event? http://jquerymobile.com/test/docs/api/events.html
If I use this event, will the script be loaded in the DOM by the time the page body references it… or will I get an object reference error?
jQuery has the
$.getScript()function you can use to retrieve external assets and evaluate them in the global scope. You can utilize the callback function for this AJAX function to do work after an asset has loaded.If you want to load multiple assets you can push the XHR object returned from jQuery AJAX functions to an array, then wait for all of the XHR objects in the array to resolve.
SINGLE
MULTIPLE
Some Documentation:
$.when(): http://api.jquery.com/jquery.when$.then(): http://api.jquery.com/jquery.then$.getScript(): http://api.jquery.com/jquery.getScriptpageInit: http://jquerymobile.com/demos/1.1.0-rc.2/docs/api/events.html