Intro
The Get Utility is one of the smaller YUI modules. Despite its size, how and when to use it can be quite complicated. It is used with css and javascript files to provide progressive loading of functionality and cross-site data retrieval. Progressive loading is a technique to load resources as they are needed on the page and not before. Cross-site data retrieval is useful for creating mashups, it allows you to request third party data. Unlike normal ajax applications, security issues prevent you from using XMLHttpRequest to call third party APIs that are hosted on different domains. In order to use XMLHttpRequests you would need to setup a proxy server hosted on your website. The Get Utility avoids this by appending a script or link tag directly to the page to retrieve the resource. It has the advantage of being lightweight, but it could also be a security issue and you shouldn’t use it without understanding the risks. Be sure you trust the 3rd party APIs you are calling and you are not exposing users to malicious javascript.
Example: Get for cross-domain JSON
The following example is based on the “Using JSON with Yahoo! Web Services” callback examples, but uses the Get Utility to request the JSON data.
First, add the YUI source files to your webpage
The method for loading javascript with the Get Utility is script. It takes a URL location for a javascript resource. Script has an optional parameter for a callback function that is called once the resource is loaded. In the example, the callback onSuccess is called by Get when the javascript resource is loaded. This callback is different from the ws_results callback that is defined in the data request which is also called when the javascript is loaded.
function ws_results(obj) {
alert(obj.ResultSet.totalResultsAvailable);
}
var searchDataReq = 'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query=Madonna&output=json&callback=ws_results';
//make Cross Domain request, callback method is onSuccess
var objTransaction = YAHOO.util.Get.script(searchDataReq,
{ onSuccess: function() {alert("file loaded"); }});
Here is a live example running this code: YUI Get Utility JSON Demo
No Comments