This example explores the simplest and most common use case for the YUI Get Utility: fetching a script with YAHOO.util.Get.script()
and making use of its contents.
Click the button to retrieve the script and output its data to the blue box. The tutorial below gives you a full description of how to use this technique.
Data returned from the loaded script will appear here after you click the button above.
In this simple example, we perform the most common task for which the Get Utility is used: retrieving a script and adding it to the page.
The contents of the script we're fetching (assets/simple_get.js
) are as follows:
The script file above defines a new namespace and then adds a property to that namespace. There are no restrictions on what we can do in the retrieved script; it can contain any correct JavaScript. When retrieved, it will be evaluated by the browser in the context of the window to which it was added. By default, it will be added to the current window and evaluated in that context.
In this page, we create a button and wire it so that when it's clicked the Get Utility will create a script node and populate it with the file above.
Above you see the important parts of this script. In the Button's click handler, we invoke YAHOO.util.Get.script
and pass it the URI of the script to be loaded. (The script can be on your server or on a third-party server; it is not restricted by the Same Origin Policy, which is why this is a popular approach for consuming JSON-based web services.) We also tell Get what we want to do once the script is loaded by defining an onSuccess
configuration property. This property consists of a function in which we can make use of the contents of assets/simple_get.js
.
The full script source used in this example appears below; read through the inline comments to get a full understanding of how to use the Get Utility in the simple use case of retrieving a script file and making use of its contents.
You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.
Copyright © 2011 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings