YUI实现JS跨域访问文件、字符串、js
2011-11-30 14:19
525 查看
学习地址:http://developer.yahoo.com/yui/get/
The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.
There are two common use cases for the Get Utility:
Cross-site data retrieval: Because XMLHttpRequest (and YUI Connection Manager, which uses XMLHttpRequest) adheres to a strict same-origin
policy, the retrieval of third-party data via XHR requires a server-side proxy. Where you control or absolutely trust a cross-domain source, you can eliminate the server-side proxy by loading a script file directly from the external domain; that script
file, which would typically contain JSON-formatted data, is executed immediately upon load. It is crucial to understand that if there is malicious code present in the loaded script there is no safe way to innoculate your users from that malicious code...the
browser will execute the code with full privileges. Never expose your users to JavaScript whose source is not absolutely trustworthy.
Progressive loading of functionality: In rich web applications, it's often useful to load some script and CSS resources only when they become necessary (based on user action). The Get Utility provides a flexible mechanism for bringing additional
resources on-demand. (Note: If you're loading YUI resources specifically, use the YUI Loader Utility; the YUI Loader employs the Get Utility under the hood
to bring in YUI components and has an intrinsic understanding of the YUI dependency tree.)
The Get Utility inserts new content into a window by creating new nodes and supplying a
Files inserted into the window in this manner are processed (and, in the case of scripts, executed) immediately upon load. While querystring parameters can be passed in the
URL, no data can be sent to the server via HTTP POST using this method. The Get Utility can only make HTTP GET requests. It can, however, interact with disparate domains. As noted above, the Get Utility is ideal for loading your own scripts or CSS progressively
(lazy-loading) or for retrieving cross-domain JSON data from sources in which you have total trust.
The YUI Connection Manager, by contrast, uses the XMLHttpRequest object to interact with the server. XMLHttpRequest is limited by a strict same
origin policy, but it supports a greater range of HTTP methods (including POST). Moreover, script data retrieved via XMLHttpRequest can be validated on the server side or in JavaScript (using, for example, the JSON
Utility) prior to being executed. As a result, Connection Manager is a more appropriate choice for rich two-way communication between browser and server and gives you more control over data before it's processed within the browser.
Getting Started
Configuring a Get Utility Transaction
Making Use of Arguments Supplied to Your Callback
Using the Get Utility to Insert Script Nodes
Using the Get Utilty to Insert CSS Files
YUI on Mobile Devices
Known Issues
Support & Community
Filing Bugs and Feature Requests
Examples: Explore examples of the Get Utility in action.
API Documentation: View the full API documentation for the Get Utility.
Release Notes: Detailed change log for the Get Utility.
License: The YUI Library is issued under a BSD license.
Download: Download the Get Utility as part of the full YUI Library at YUILibrary.com.
The Get Utility's only dependency is the Yahoo Global Object. To use the Get Utility, include the following source files in your web page:
Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components;
the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Note: If you are loading components via the YUI Loader, this component is included in the YUI Loader package — you do not need to load it separately.
If YUI Loader is on the page, so is the Get Utility.
Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important
information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the
of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
With the Get Utility present, you can make use of it to fetch script (
and/or CSS (
the page. The
each take the following arguments:
URL(s): A string or an array of strings designating the URL(s) you wish to load into the page;
options: An optional object containing configuration information for the transaction; see the Configuring a Get Utility Transaction section below for the full
list of configuraton members you can include here.
A sample request for a file might look like this:
The Get Utility is configured via the second argument to the
This optional argument comprises an object containing one or more of the following fields:
As noted in the section above, your callback method (whether
will have access to the
the configuration object, assuming you provided one. But the
is just one of several fields included in the object passed to your callback. Here's a summary of the fields contained in that argument object:
All of these fields are accessible on the object passed to your
When you use the
to add one or more script nodes to the page, the Get Utility implements the following steps:
A script node is appended to the target
the first script file requested;
the
to the specified URL;
the script, in a successful transaction, is loaded and executed;
the script node's
the Get Utility checks to see if more URLs remain to be loaded; if so, it recurses to step 1;
if this was the last of the URLs specified for this transaction, the Get Utility invokes the
(if one has been specified);
The following is the general code pattern used to get scripts:
When you use the
add one or more CSS files to the page, the Get Utility follows the same steps described above for scripts. Generally speaking, the same code pattern holds as well. Note that Firefox and Safari at present do not support the load event on link nodes, so it is
possible for CSS requests to load out of order in those browsers. This can result in a different progressive display of styled in Firefox and Safari versus other browsers during CSS loading.
About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's
Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:
Screen size: You have a much smaller canvas;
Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.
There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific
components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started
as you contemplate how your YUI-based application will render in the mobile world.
More Information:
Challenges of Interface Design for Mobile Devices - YUI Blog article by Lucas Pettinati, Yahoo! Sr. Interaction Designer.
Performance Research, Part 5: iPhone Cacheability - Making it Stick - YUI Blog article by Tenni Theurer and Wayne Shea from the Yahoo! Exceptional Performance Team
YUI 2: Get Utility
The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.There are two common use cases for the Get Utility:
Cross-site data retrieval: Because XMLHttpRequest (and YUI Connection Manager, which uses XMLHttpRequest) adheres to a strict same-origin
policy, the retrieval of third-party data via XHR requires a server-side proxy. Where you control or absolutely trust a cross-domain source, you can eliminate the server-side proxy by loading a script file directly from the external domain; that script
file, which would typically contain JSON-formatted data, is executed immediately upon load. It is crucial to understand that if there is malicious code present in the loaded script there is no safe way to innoculate your users from that malicious code...the
browser will execute the code with full privileges. Never expose your users to JavaScript whose source is not absolutely trustworthy.
Progressive loading of functionality: In rich web applications, it's often useful to load some script and CSS resources only when they become necessary (based on user action). The Get Utility provides a flexible mechanism for bringing additional
resources on-demand. (Note: If you're loading YUI resources specifically, use the YUI Loader Utility; the YUI Loader employs the Get Utility under the hood
to bring in YUI components and has an intrinsic understanding of the YUI dependency tree.)
What Is the Difference Between the Get Utility and the Connection Manager?
The Get Utility inserts new content into a window by creating new nodes and supplying a srcattribute.
Files inserted into the window in this manner are processed (and, in the case of scripts, executed) immediately upon load. While querystring parameters can be passed in the
srcattribute
URL, no data can be sent to the server via HTTP POST using this method. The Get Utility can only make HTTP GET requests. It can, however, interact with disparate domains. As noted above, the Get Utility is ideal for loading your own scripts or CSS progressively
(lazy-loading) or for retrieving cross-domain JSON data from sources in which you have total trust.
The YUI Connection Manager, by contrast, uses the XMLHttpRequest object to interact with the server. XMLHttpRequest is limited by a strict same
origin policy, but it supports a greater range of HTTP methods (including POST). Moreover, script data retrieved via XMLHttpRequest can be validated on the server side or in JavaScript (using, for example, the JSON
Utility) prior to being executed. As a result, Connection Manager is a more appropriate choice for rich two-way communication between browser and server and gives you more control over data before it's processed within the browser.
On This Page:
Getting StartedConfiguring a Get Utility Transaction
Making Use of Arguments Supplied to Your Callback
Using the Get Utility to Insert Script Nodes
Using the Get Utilty to Insert CSS Files
YUI on Mobile Devices
Known Issues
Support & Community
Filing Bugs and Feature Requests
Quick Links:
Examples: Explore examples of the Get Utility in action.API Documentation: View the full API documentation for the Get Utility.
Release Notes: Detailed change log for the Get Utility.
License: The YUI Library is issued under a BSD license.
Download: Download the Get Utility as part of the full YUI Library at YUILibrary.com.
Getting Started
The Get Utility's only dependency is the Yahoo Global Object. To use the Get Utility, include the following source files in your web page:<!-- Dependencies --> <script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js" ></script> <script src="http://yui.yahooapis.com/2.9.0/build/get/get-min.js" ></script>
YUI Dependency Configurator:
Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components;the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.
Note: If you are loading components via the YUI Loader, this component is included in the YUI Loader package — you do not need to load it separately.
If YUI Loader is on the page, so is the Get Utility.
Where these files come from: The files included using the text above will be served from Yahoo! servers; see "Serving YUI Files from Yahoo!" for important
information about this service. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the
-debugversions
of YUI JavaScript files, please download the library distribution and host the files on your own server.
Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.
With the Get Utility present, you can make use of it to fetch script (
YAHOO.util.Get.script())
and/or CSS (
YAHOO.util.Get.css()) resources to
the page. The
scriptand
cssmethods
each take the following arguments:
URL(s): A string or an array of strings designating the URL(s) you wish to load into the page;
options: An optional object containing configuration information for the transaction; see the Configuring a Get Utility Transaction section below for the full
list of configuraton members you can include here.
A sample request for a file might look like this:
var objTransaction = YAHOO.util.Get.script("http://json.org/json.js", { onSuccess: function() { alert("file loaded"); } }); //objTransaction will be an object with a single field, tId, //which is a unique identifier of the transaction following the pattern //"q0", "q1", "q2"..."qn".
Configuring a Get Utility Transaction
The Get Utility is configured via the second argument to the scriptor
cssmethod.
This optional argument comprises an object containing one or more of the following fields:
Configuration Option | Purpose |
---|---|
onSuccess | (function) Callback method invoked by Get Utility when the requested file(s) have loaded successfully. |
onFailure | (function) Callback method invoked by Get Utility when an error is detected or abortis called. |
onProgress | (function) Callback method invoked by Get Utility after each node is inserted. |
onTimeout | (function) Callback method invoked by Get Utility if a timeout is detected. |
win | (obj) The windowinto which the loaded resource(s) will be inserted. Default: the current window. |
scope | (object) The execution scope in which the onSuccessor onFailurecallback will run. Default: the current window. |
data | (any) Data to pass as an argument to onSuccessor onFailurecallbacks. Default: null. |
autopurge | (boolean) If set to true, script nodes will automatically be removed every 20 transactions (this number is globally configurable via the Y.Get.PURGE_THRESHproperty); script nodes can be safely removed in most cases, as their contents (having executed) remain available. CSS nodes should not have this set to true as it will remove the CSS rules. Default: truefor script nodes, falsefor CSS nodes. |
timeout | (int) Number of milliseconds to wait for a script to finish loading before timing out |
Making Use of Arguments Supplied to Your Callback
As noted in the section above, your callback method (whether onSuccessor
onFailure)
will have access to the
datamember supplied in
the configuration object, assuming you provided one. But the
datamember
is just one of several fields included in the object passed to your callback. Here's a summary of the fields contained in that argument object:
Field | Contents |
---|---|
tId | (string) The unique identifier for this transaction; this string is available as the tIdmember of the object returned to you upon calling the scriptor cssmethod. |
data | (any) The datafield you passed in your configuration object when the scriptor cssmethod was called. Default: null. |
nodes | (array) An array containing references to node(s) created in processing the transaction. These will be script nodes for JavaScript and link nodes for CSS. |
win | (obj) The window object in which the nodes were created. |
purge() | (function) Calling the returned purge()method will immediately remove the created nodes. This is safe and prudent for JavaScript nodes, which do not need to persist. If CSS nodes are purged, the rules they contain are no longer available and the page will repaint accordingly. |
onSuccesscallback:
var successHandler = function(o) { //Here, o contains all of the fields described in the table //above: o.purge(); //removes the script node immediately after executing; YAHOO.log(o.data); //the data you passed in your configuration //object } var objTransaction = YAHOO.util.Get.script("http://json.org/json.js", { onSuccess: successHandler, data: { field1: value1, field2: value2 } });
Using the Get Utility to Insert Script Nodes
When you use the YAHOO.util.Get.script()method
to add one or more script nodes to the page, the Get Utility implements the following steps:
A script node is appended to the target
windowfor
the first script file requested;
the
srcattribute of the new script node is set
to the specified URL;
the script, in a successful transaction, is loaded and executed;
the script node's
loadevent fires;
the Get Utility checks to see if more URLs remain to be loaded; if so, it recurses to step 1;
if this was the last of the URLs specified for this transaction, the Get Utility invokes the
onSuccesscallback
(if one has been specified);
The following is the general code pattern used to get scripts:
var handlerData = { //data you wish to pass to your success or failure //handlers. }; var successHandler = function(oData) { //code to execute when all requested scripts have been //loaded; this code can make use of the contents of those //scripts, whether it's functional code or JSON data. }; var aURLs = [ "/url1.js", "/url2.js", "/url3.js" //and so on ]; YAHOO.util.Get.script(aURLs, { onSuccess: successHandler, data: handlerData });
Using the Get Utility to Insert CSS Files
When you use the YAHOO.util.Get.css()method to
add one or more CSS files to the page, the Get Utility follows the same steps described above for scripts. Generally speaking, the same code pattern holds as well. Note that Firefox and Safari at present do not support the load event on link nodes, so it is
possible for CSS requests to load out of order in those browsers. This can result in a different progressive display of styled in Firefox and Safari versus other browsers during CSS loading.
YUI on Mobile: Using Get Utility with "A-Grade" Mobile Browsers
About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple'sSafari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:
Screen size: You have a much smaller canvas;
Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.
There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific
components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started
as you contemplate how your YUI-based application will render in the mobile world.
More Information:
Challenges of Interface Design for Mobile Devices - YUI Blog article by Lucas Pettinati, Yahoo! Sr. Interaction Designer.
Performance Research, Part 5: iPhone Cacheability - Making it Stick - YUI Blog article by Tenni Theurer and Wayne Shea from the Yahoo! Exceptional Performance Team
相关文章推荐
- .NET通过配置文件的方式实现静态js文件跨域访问
- js实现跨域访问的三种方法
- js判断请求的url是否可访问,支持跨域判断的实现方法
- 人人js 版SDK,跨域文件xd_receiver.htm作用、实现研究备忘
- YUI实现跨域交换文件
- 三种方法实现js跨域访问
- 三种方法实现js跨域访问
- 关于JS访问文件服务器的HTTP文件地址实现文件下载
- Ajax跨域的解决办法:载入javascript(js)文件实现无刷新更新数据(转载)
- 三种方法实现js跨域访问
- 三种方法实现js跨域访问(转载)
- 使用 JS 访问服务器地址实现下载文件
- html5的postmessage实现js前端跨域访问及调用解决方案
- 解决ajax不能访问本地文件问题(利用js跨域原理)
- 三种方法实现js跨域访问
- js 设置header,实现跨域访问
- js实现跨域访问的三种方法
- 三种方法实现js跨域访问
- 利用cors,实现js跨域访问Tomcat下资源
- js实现跨域访问