2012-04-09 53 views
4

我想這是一個常見的情況,很驚訝沒有找到答案。所以這裏它去...jqueryMobile:如何加載外部Javascript

我的jquerymobile網站內的一些頁面正在使用外部javascripts。我不希望這些腳本加載到網站的每個頁面上。它是移動的,它應該快速加載。

如何加載外部JavaScript,以便在需要引用它時在DOM中可用。我發現這個似乎有一個很好的技術的堆棧文章:Using Javascript to load other external Javascripts

如果我動態加載這個外部JavaScript,我應該使用pageinit事件? http://jquerymobile.com/test/docs/api/events.html

如果我使用這個事件,腳本會在頁面主體引用它的時候加載到DOM中......還是會得到一個對象引用錯誤?

回答

3

jQuery具有$.getScript()函數,您可以使用該函數來檢索外部資產並在全局範圍內評估它們。您可以使用此AJAX功能的回調函數在資產加載後執行工作。

如果您想要加載多個資產,您可以將從jQuery AJAX函數返回的XHR對象推送到一個數組,然後等待數組中的所有XHR對象解析。

//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 
    }); 
}); 

$(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 
    }); 
}); 

一些文檔:

+0

愛與單項和多項的例子。太棒了! – Lucas 2012-04-10 00:37:50