5

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?

Community
  • 1
  • 1
Lucas
  • 614
  • 7
  • 19

1 Answers1

4

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 get
    var 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 array
    for (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:

Jasper
  • 75,717
  • 14
  • 151
  • 146