Debian Codegraph @

closure-library/closure/goog/net/jsloader.js

raw
1 // Copyright 2011 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview A utility to load JavaScript files via DOM script tags.
17 * Refactored from goog.net.Jsonp. Works cross-domain.
18 *
19 */
20
21 goog.provide('goog.net.jsloader');
22 goog.provide('goog.net.jsloader.Error');
23 goog.provide('goog.net.jsloader.ErrorCode');
24 goog.provide('goog.net.jsloader.Options');
25
26 goog.require('goog.array');
27 goog.require('goog.async.Deferred');
28 goog.require('goog.debug.Error');
29 goog.require('goog.dom');
30 goog.require('goog.dom.TagName');
31 goog.require('goog.dom.safe');
32 goog.require('goog.html.TrustedResourceUrl');
33 goog.require('goog.object');
34
35
36 /**
37 * The name of the property of goog.global under which the JavaScript
38 * verification object is stored by the loaded script.
39 * @private {string}
40 */
41 goog.net.jsloader.GLOBAL_VERIFY_OBJS_ = 'closure_verification';
42
43
44 /**
45 * The default length of time, in milliseconds, we are prepared to wait for a
46 * load request to complete.
47 * @type {number}
48 */
49 goog.net.jsloader.DEFAULT_TIMEOUT = 5000;
50
51
52 /**
53 * Optional parameters for goog.net.jsloader.send.
54 * timeout: The length of time, in milliseconds, we are prepared to wait
55 * for a load request to complete, or 0 or negative for no timeout. Default
56 * is 5 seconds.
57 * document: The HTML document under which to load the JavaScript. Default is
58 * the current document.
59 * cleanupWhenDone: If true clean up the script tag after script completes to
60 * load. This is important if you just want to read data from the JavaScript
61 * and then throw it away. Default is false.
62 * attributes: Additional attributes to set on the script tag.
63 *
64 * @typedef {{
65 * timeout: (number|undefined),
66 * document: (HTMLDocument|undefined),
67 * cleanupWhenDone: (boolean|undefined),
68 * attributes: (!Object<string, string>|undefined)
69 * }}
70 */
71 goog.net.jsloader.Options;
72
73
74 /**
75 * Scripts (URIs) waiting to be loaded.
76 * @private {!Array<!goog.html.TrustedResourceUrl>}
77 */
78 goog.net.jsloader.scriptsToLoad_ = [];
79
80
81 /**
82 * The deferred result of loading the URIs in scriptsToLoad_.
83 * We need to return this to a caller that wants to load URIs while
84 * a deferred is already working on them.
85 * @private {!goog.async.Deferred<null>}
86 */
87 goog.net.jsloader.scriptLoadingDeferred_;
88
89
90
91 /**
92 * Loads and evaluates the JavaScript files at the specified URIs, guaranteeing
93 * the order of script loads.
94 *
95 * Because we have to load the scripts in serial (load script 1, exec script 1,
96 * load script 2, exec script 2, and so on), this will be slower than doing
97 * the network fetches in parallel.
98 *
99 * If you need to load a large number of scripts but dependency order doesn't
100 * matter, you should just call goog.net.jsloader.safeLoad N times.
101 *
102 * If you need to load a large number of scripts on the same domain,
103 * you may want to use goog.module.ModuleLoader.
104 *
105 * @param {Array<!goog.html.TrustedResourceUrl>} trustedUris The URIs to load.
106 * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
107 * goog.net.jsloader.options documentation for details.
108 * @return {!goog.async.Deferred} The deferred result, that may be used to add
109 * callbacks
110 */
111 goog.net.jsloader.safeLoadMany = function(trustedUris, opt_options) {
112 // Loading the scripts in serial introduces asynchronosity into the flow.
113 // Therefore, there are race conditions where client A can kick off the load
114 // sequence for client B, even though client A's scripts haven't all been
115 // loaded yet.
116 //
117 // To work around this issue, all module loads share a queue.
118 if (!trustedUris.length) {
119 return goog.async.Deferred.succeed(null);
120 }
121
122 var isAnotherModuleLoading = goog.net.jsloader.scriptsToLoad_.length;
123 goog.array.extend(goog.net.jsloader.scriptsToLoad_, trustedUris);
124 if (isAnotherModuleLoading) {
125 // jsloader is still loading some other scripts.
126 // In order to prevent the race condition noted above, we just add
127 // these URIs to the end of the scripts' queue and return the deferred
128 // result of the ongoing script load, so the caller knows when they
129 // finish loading.
130 return goog.net.jsloader.scriptLoadingDeferred_;
131 }
132
133 trustedUris = goog.net.jsloader.scriptsToLoad_;
134 var popAndLoadNextScript = function() {
135 var trustedUri = trustedUris.shift();
136 var deferred = goog.net.jsloader.safeLoad(trustedUri, opt_options);
137 if (trustedUris.length) {
138 deferred.addBoth(popAndLoadNextScript);
139 }
140 return deferred;
141 };
142 goog.net.jsloader.scriptLoadingDeferred_ = popAndLoadNextScript();
143 return goog.net.jsloader.scriptLoadingDeferred_;
144 };
145
146
147 /**
148 * Loads and evaluates a JavaScript file.
149 * When the script loads, a user callback is called.
150 * It is the client's responsibility to verify that the script ran successfully.
151 *
152 * @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.
153 * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See
154 * goog.net.jsloader.Options documentation for details.
155 * @return {!goog.async.Deferred} The deferred result, that may be used to add
156 * callbacks and/or cancel the transmission.
157 * The error callback will be called with a single goog.net.jsloader.Error
158 * parameter.
159 */
160 goog.net.jsloader.safeLoad = function(trustedUri, opt_options) {
161 var options = opt_options || {};
162 var doc = options.document || document;
163 var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);
164
165 var script = goog.dom.createElement(goog.dom.TagName.SCRIPT);
166 var request = {script_: script, timeout_: undefined};
167 var deferred = new goog.async.Deferred(goog.net.jsloader.cancel_, request);
168
169 // Set a timeout.
170 var timeout = null;
171 var timeoutDuration = goog.isDefAndNotNull(options.timeout) ?
172 options.timeout :
173 goog.net.jsloader.DEFAULT_TIMEOUT;
174 if (timeoutDuration > 0) {
175 timeout = window.setTimeout(function() {
176 goog.net.jsloader.cleanup_(script, true);
177 deferred.errback(
178 new goog.net.jsloader.Error(
179 goog.net.jsloader.ErrorCode.TIMEOUT,
180 'Timeout reached for loading script ' + uri));
181 }, timeoutDuration);
182 request.timeout_ = timeout;
183 }
184
185 // Hang the user callback to be called when the script completes to load.
186 // NOTE(user): This callback will be called in IE even upon error. In any
187 // case it is the client's responsibility to verify that the script ran
188 // successfully.
189 script.onload = script.onreadystatechange = function() {
190 if (!script.readyState || script.readyState == 'loaded' ||
191 script.readyState == 'complete') {
192 var removeScriptNode = options.cleanupWhenDone || false;
193 goog.net.jsloader.cleanup_(script, removeScriptNode, timeout);
194 deferred.callback(null);
195 }
196 };
197
198 // Add an error callback.
199 // NOTE(user): Not supported in IE.
200 script.onerror = function() {
201 goog.net.jsloader.cleanup_(script, true, timeout);
202 deferred.errback(
203 new goog.net.jsloader.Error(
204 goog.net.jsloader.ErrorCode.LOAD_ERROR,
205 'Error while loading script ' + uri));
206 };
207
208 var properties = options.attributes || {};
209 goog.object.extend(
210 properties, {'type': 'text/javascript', 'charset': 'UTF-8'});
211 goog.dom.setProperties(script, properties);
212 // NOTE(user): Safari never loads the script if we don't set the src
213 // attribute before appending.
214 goog.dom.safe.setScriptSrc(script, trustedUri);
215 var scriptParent = goog.net.jsloader.getScriptParentElement_(doc);
216 scriptParent.appendChild(script);
217
218 return deferred;
219 };
220
221
222 /**
223 * Loads a JavaScript file and verifies it was evaluated successfully, using a
224 * verification object.
225 * The verification object is set by the loaded JavaScript at the end of the
226 * script.
227 * We verify this object was set and return its value in the success callback.
228 * If the object is not defined we trigger an error callback.
229 *
230 * @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.
231 * @param {string} verificationObjName The name of the verification object that
232 * the loaded script should set.
233 * @param {goog.net.jsloader.Options} options Optional parameters. See
234 * goog.net.jsloader.Options documentation for details.
235 * @return {!goog.async.Deferred} The deferred result, that may be used to add
236 * callbacks and/or cancel the transmission.
237 * The success callback will be called with a single parameter containing
238 * the value of the verification object.
239 * The error callback will be called with a single goog.net.jsloader.Error
240 * parameter.
241 */
242 goog.net.jsloader.safeLoadAndVerify = function(
243 trustedUri, verificationObjName, options) {
244 // Define the global objects variable.
245 if (!goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]) {
246 goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_] = {};
247 }
248 var verifyObjs = goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_];
249 var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);
250
251 // Verify that the expected object does not exist yet.
252 if (goog.isDef(verifyObjs[verificationObjName])) {
253 // TODO(user): Error or reset variable?
254 return goog.async.Deferred.fail(
255 new goog.net.jsloader.Error(
256 goog.net.jsloader.ErrorCode.VERIFY_OBJECT_ALREADY_EXISTS,
257 'Verification object ' + verificationObjName +
258 ' already defined.'));
259 }
260
261 // Send request to load the JavaScript.
262 var sendDeferred = goog.net.jsloader.safeLoad(trustedUri, options);
263
264 // Create a deferred object wrapping the send result.
265 var deferred =
266 new goog.async.Deferred(goog.bind(sendDeferred.cancel, sendDeferred));
267
268 // Call user back with object that was set by the script.
269 sendDeferred.addCallback(function() {
270 var result = verifyObjs[verificationObjName];
271 if (goog.isDef(result)) {
272 deferred.callback(result);
273 delete verifyObjs[verificationObjName];
274 } else {
275 // Error: script was not loaded properly.
276 deferred.errback(
277 new goog.net.jsloader.Error(
278 goog.net.jsloader.ErrorCode.VERIFY_ERROR, 'Script ' + uri +
279 ' loaded, but verification object ' + verificationObjName +
280 ' was not defined.'));
281 }
282 });
283
284 // Pass error to new deferred object.
285 sendDeferred.addErrback(function(error) {
286 if (goog.isDef(verifyObjs[verificationObjName])) {
287 delete verifyObjs[verificationObjName];
288 }
289 deferred.errback(error);
290 });
291
292 return deferred;
293 };
294
295
296 /**
297 * Gets the DOM element under which we should add new script elements.
298 * How? Take the first head element, and if not found take doc.documentElement,
299 * which always exists.
300 *
301 * @param {!HTMLDocument} doc The relevant document.
302 * @return {!Element} The script parent element.
303 * @private
304 */
305 goog.net.jsloader.getScriptParentElement_ = function(doc) {
306 var headElements = goog.dom.getElementsByTagName(goog.dom.TagName.HEAD, doc);
307 if (!headElements || goog.array.isEmpty(headElements)) {
308 return doc.documentElement;
309 } else {
310 return headElements[0];
311 }
312 };
313
314
315 /**
316 * Cancels a given request.
317 * @this {{script_: Element, timeout_: number}} The request context.
318 * @private
319 */
320 goog.net.jsloader.cancel_ = function() {
321 var request = this;
322 if (request && request.script_) {
323 var scriptNode = request.script_;
324 if (scriptNode && scriptNode.tagName == goog.dom.TagName.SCRIPT) {
325 goog.net.jsloader.cleanup_(scriptNode, true, request.timeout_);
326 }
327 }
328 };
329
330
331 /**
332 * Removes the script node and the timeout.
333 *
334 * @param {Node} scriptNode The node to be cleaned up.
335 * @param {boolean} removeScriptNode If true completely remove the script node.
336 * @param {?number=} opt_timeout The timeout handler to cleanup.
337 * @private
338 */
339 goog.net.jsloader.cleanup_ = function(
340 scriptNode, removeScriptNode, opt_timeout) {
341 if (goog.isDefAndNotNull(opt_timeout)) {
342 goog.global.clearTimeout(opt_timeout);
343 }
344
345 scriptNode.onload = goog.nullFunction;
346 scriptNode.onerror = goog.nullFunction;
347 scriptNode.onreadystatechange = goog.nullFunction;
348
349 // Do this after a delay (removing the script node of a running script can
350 // confuse older IEs).
351 if (removeScriptNode) {
352 window.setTimeout(function() { goog.dom.removeNode(scriptNode); }, 0);
353 }
354 };
355
356
357 /**
358 * Possible error codes for jsloader.
359 * @enum {number}
360 */
361 goog.net.jsloader.ErrorCode = {
362 LOAD_ERROR: 0,
363 TIMEOUT: 1,
364 VERIFY_ERROR: 2,
365 VERIFY_OBJECT_ALREADY_EXISTS: 3
366 };
367
368
369
370 /**
371 * A jsloader error.
372 *
373 * @param {goog.net.jsloader.ErrorCode} code The error code.
374 * @param {string=} opt_message Additional message.
375 * @constructor
376 * @extends {goog.debug.Error}
377 * @final
378 */
379 goog.net.jsloader.Error = function(code, opt_message) {
380 var msg = 'Jsloader error (code #' + code + ')';
381 if (opt_message) {
382 msg += ': ' + opt_message;
383 }
384 goog.net.jsloader.Error.base(this, 'constructor', msg);
385
386 /**
387 * The code for this error.
388 *
389 * @type {goog.net.jsloader.ErrorCode}
390 */
391 this.code = code;
392 };
393 goog.inherits(goog.net.jsloader.Error, goog.debug.Error);