Jquerymobile: How To Load External Javascripts
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
Solution 1:
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
//get remote asset when a specified page is initialized by jQuery Mobile
$(document).delegate('#my-map-page', 'pageinit', function () {
$.getScript('http://maps.google.com/maps/api/js?sensor=false', function () {
//the code has now been evaluated and you can utilize it here
});
});
MULTIPLE
$(document).delegate('#my-map-page', 'pageinit', function () {
//setup array for XHR objects and one for the URLs of the assets you want to getvar jqXHRs = [],
scripts = ['http://maps.google.com/maps/api/js?sensor=false', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'];
//loop through the script URLs and create an AJAX request to get them,//also add the XHR object for the request to an arrayfor (var i = 0, len = scripts.length; i < len; i++ ) {
jqXHR.push($.getScript(scripts[i]));
}
//use the array of XHR objects we created to wait for all assets to load
$.when(jqXHR).then(function () {
//all the scripts have loaded and are evaluated, do work
});
});
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
Post a Comment for "Jquerymobile: How To Load External Javascripts"