1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
|
/*
@VaadinApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.gwt.core.client.Duration;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.LinkElement;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.ObjectElement;
import com.google.gwt.dom.client.ScriptElement;
import com.google.gwt.user.client.Timer;
/**
* ResourceLoader lets you dynamically include external scripts and styles on
* the page and lets you know when the resource has been loaded.
*
* You can also preload resources, allowing them to get cached by the browser
* without being evaluated. This enables downloading multiple resources at once
* while still controlling in which order e.g. scripts are executed.
*
* @author Vaadin Ltd
* @version @VERSION@
* @since 7.0.0
*/
public class ResourceLoader {
/**
* Event fired when a resource has been loaded.
*/
public static class ResourceLoadEvent {
private ResourceLoader loader;
private String resourceUrl;
private final boolean preload;
/**
* Creates a new event.
*
* @param loader
* the resource loader that has loaded the resource
* @param resourceUrl
* the url of the loaded resource
* @param preload
* true if the resource has only been preloaded, false if
* it's fully loaded
*/
public ResourceLoadEvent(ResourceLoader loader, String resourceUrl,
boolean preload) {
this.loader = loader;
this.resourceUrl = resourceUrl;
this.preload = preload;
}
/**
* Gets the resource loader that has fired this event
*
* @return the resource loader
*/
public ResourceLoader getResourceLoader() {
return loader;
}
/**
* Gets the absolute url of the loaded resource.
*
* @return the absolute url of the loaded resource
*/
public String getResourceUrl() {
return resourceUrl;
}
/**
* Returns true if the resource has been preloaded, false if it's fully
* loaded
*
* @see ResourceLoader#preloadResource(String, ResourceLoadListener)
*
* @return true if the resource has been preloaded, false if it's fully
* loaded
*/
public boolean isPreload() {
return preload;
}
}
/**
* Event listener that gets notified when a resource has been loaded
*/
public interface ResourceLoadListener {
/**
* Notifies this ResourceLoadListener that a resource has been loaded.
* Some browsers do not support any way of detecting load errors. In
* these cases, onLoad will be called regardless of the status.
*
* @see ResourceLoadEvent
*
* @param event
* a resource load event with information about the loaded
* resource
*/
public void onLoad(ResourceLoadEvent event);
/**
* Notifies this ResourceLoadListener that a resource could not be
* loaded, e.g. because the file could not be found or because the
* server did not respond. Some browsers do not support any way of
* detecting load errors. In these cases, onLoad will be called
* regardless of the status.
*
* @see ResourceLoadEvent
*
* @param event
* a resource load event with information about the resource
* that could not be loaded.
*/
public void onError(ResourceLoadEvent event);
}
private static final ResourceLoader INSTANCE = GWT
.create(ResourceLoader.class);
private ApplicationConnection connection;
private final Set<String> loadedResources = new HashSet<String>();
private final Set<String> preloadedResources = new HashSet<String>();
private final Map<String, Collection<ResourceLoadListener>> loadListeners = new HashMap<String, Collection<ResourceLoadListener>>();
private final Map<String, Collection<ResourceLoadListener>> preloadListeners = new HashMap<String, Collection<ResourceLoadListener>>();
private final Element head;
/**
* Creates a new resource loader. You should generally not create you own
* resource loader, but instead use {@link ResourceLoader#get()} to get an
* instance.
*/
protected ResourceLoader() {
Document document = Document.get();
head = document.getElementsByTagName("head").getItem(0);
// detect already loaded scripts and stylesheets
NodeList<Element> scripts = document.getElementsByTagName("script");
for (int i = 0; i < scripts.getLength(); i++) {
ScriptElement element = ScriptElement.as(scripts.getItem(i));
String src = element.getSrc();
if (src != null && src.length() != 0) {
loadedResources.add(src);
}
}
NodeList<Element> links = document.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); i++) {
LinkElement linkElement = LinkElement.as(links.getItem(i));
String rel = linkElement.getRel();
String href = linkElement.getHref();
if ("stylesheet".equalsIgnoreCase(rel) && href != null
&& href.length() != 0) {
loadedResources.add(href);
}
}
}
/**
* Returns the default ResourceLoader
*
* @return the default ResourceLoader
*/
public static ResourceLoader get() {
return INSTANCE;
}
/**
* Load a script and notify a listener when the script is loaded. Calling
* this method when the script is currently loading or already loaded
* doesn't cause the script to be loaded again, but the listener will still
* be notified when appropriate.
*
*
* @param scriptUrl
* the url of the script to load
* @param resourceLoadListener
* the listener that will get notified when the script is loaded
*/
public void loadScript(final String scriptUrl,
final ResourceLoadListener resourceLoadListener) {
final String url = getAbsoluteUrl(scriptUrl);
ResourceLoadEvent event = new ResourceLoadEvent(this, url, false);
if (loadedResources.contains(url)) {
if (resourceLoadListener != null) {
resourceLoadListener.onLoad(event);
}
return;
}
if (preloadListeners.containsKey(url)) {
// Preload going on, continue when preloaded
preloadResource(url, new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
loadScript(url, resourceLoadListener);
}
@Override
public void onError(ResourceLoadEvent event) {
// Preload failed -> signal error to own listener
if (resourceLoadListener != null) {
resourceLoadListener.onError(event);
}
}
});
return;
}
if (addListener(url, resourceLoadListener, loadListeners)) {
ScriptElement scriptTag = Document.get().createScriptElement();
scriptTag.setSrc(url);
scriptTag.setType("text/javascript");
addOnloadHandler(scriptTag, new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
fireLoad(event);
}
@Override
public void onError(ResourceLoadEvent event) {
fireError(event);
}
}, event);
head.appendChild(scriptTag);
}
}
private static String getAbsoluteUrl(String url) {
AnchorElement a = Document.get().createAnchorElement();
a.setHref(url);
return a.getHref();
}
/**
* Download a resource and notify a listener when the resource is loaded
* without attempting to interpret the resource. When a resource has been
* preloaded, it will be present in the browser's cache (provided the HTTP
* headers allow caching), making a subsequent load operation complete
* without having to wait for the resource to be downloaded again.
*
* Calling this method when the resource is currently loading, currently
* preloading, already preloaded or already loaded doesn't cause the
* resource to be preloaded again, but the listener will still be notified
* when appropriate.
*
* @param url
* the url of the resource to preload
* @param resourceLoadListener
* the listener that will get notified when the resource is
* preloaded
*/
public void preloadResource(String url,
ResourceLoadListener resourceLoadListener) {
url = getAbsoluteUrl(url);
ResourceLoadEvent event = new ResourceLoadEvent(this, url, true);
if (loadedResources.contains(url) || preloadedResources.contains(url)) {
// Already loaded or preloaded -> just fire listener
if (resourceLoadListener != null) {
resourceLoadListener.onLoad(event);
}
return;
}
if (addListener(url, resourceLoadListener, preloadListeners)
&& !loadListeners.containsKey(url)) {
// Inject loader element if this is the first time this is preloaded
// AND the resources isn't already being loaded in the normal way
Element element = getPreloadElement(url);
addOnloadHandler(element, new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
fireLoad(event);
}
@Override
public void onError(ResourceLoadEvent event) {
fireError(event);
}
}, event);
// TODO Remove object when loaded (without causing spinner in FF)
Document.get().getBody().appendChild(element);
}
}
private static Element getPreloadElement(String url) {
if (BrowserInfo.get().isIE()) {
ScriptElement element = Document.get().createScriptElement();
element.setSrc(url);
element.setType("text/cache");
return element;
} else {
ObjectElement element = Document.get().createObjectElement();
element.setData(url);
element.setType("text/plain");
element.setHeight("0px");
element.setWidth("0px");
return element;
}
}
private native void addOnloadHandler(Element element,
ResourceLoadListener listener, ResourceLoadEvent event)
/*-{
element.onload = $entry(function() {
element.onload = null;
element.onerror = null;
element.onreadystatechange = null;
listener.@com.vaadin.terminal.gwt.client.ResourceLoader.ResourceLoadListener::onLoad(Lcom/vaadin/terminal/gwt/client/ResourceLoader$ResourceLoadEvent;)(event);
});
element.onerror = $entry(function() {
element.onload = null;
element.onerror = null;
element.onreadystatechange = null;
listener.@com.vaadin.terminal.gwt.client.ResourceLoader.ResourceLoadListener::onError(Lcom/vaadin/terminal/gwt/client/ResourceLoader$ResourceLoadEvent;)(event);
});
element.onreadystatechange = function() {
if ("loaded" === element.readyState || "complete" === element.readyState ) {
element.onload(arguments[0]);
}
};
}-*/;
/**
* Load a stylesheet and notify a listener when the stylesheet is loaded.
* Calling this method when the stylesheet is currently loading or already
* loaded doesn't cause the stylesheet to be loaded again, but the listener
* will still be notified when appropriate.
*
* @param stylesheetUrl
* the url of the stylesheet to load
* @param resourceLoadListener
* the listener that will get notified when the stylesheet is
* loaded
*/
public void loadStylesheet(final String stylesheetUrl,
final ResourceLoadListener resourceLoadListener) {
final String url = getAbsoluteUrl(stylesheetUrl);
final ResourceLoadEvent event = new ResourceLoadEvent(this, url, false);
if (loadedResources.contains(url)) {
if (resourceLoadListener != null) {
resourceLoadListener.onLoad(event);
}
return;
}
if (preloadListeners.containsKey(url)) {
// Preload going on, continue when preloaded
preloadResource(url, new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
loadStylesheet(url, resourceLoadListener);
}
@Override
public void onError(ResourceLoadEvent event) {
// Preload failed -> signal error to own listener
if (resourceLoadListener != null) {
resourceLoadListener.onError(event);
}
}
});
return;
}
if (addListener(url, resourceLoadListener, loadListeners)) {
LinkElement linkElement = Document.get().createLinkElement();
linkElement.setRel("stylesheet");
linkElement.setType("text/css");
linkElement.setHref(url);
if (BrowserInfo.get().isSafari()) {
// Safari doesn't fire any events for link elements
// See http://www.phpied.com/when-is-a-stylesheet-really-loaded/
Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
private final Duration duration = new Duration();
@Override
public boolean execute() {
int styleSheetLength = getStyleSheetLength(url);
if (getStyleSheetLength(url) > 0) {
fireLoad(event);
return false; // Stop repeating
} else if (styleSheetLength == 0) {
// "Loaded" empty sheet -> most likely 404 error
fireError(event);
return true;
} else if (duration.elapsedMillis() > 60 * 1000) {
fireError(event);
return false;
} else {
return true; // Continue repeating
}
}
}, 10);
} else {
addOnloadHandler(linkElement, new ResourceLoadListener() {
@Override
public void onLoad(ResourceLoadEvent event) {
// Chrome && IE fires load for errors, must check
// stylesheet data
if (BrowserInfo.get().isChrome()
|| BrowserInfo.get().isIE()) {
int styleSheetLength = getStyleSheetLength(url);
// Error if there's an empty stylesheet
if (styleSheetLength == 0) {
fireError(event);
return;
}
}
fireLoad(event);
}
@Override
public void onError(ResourceLoadEvent event) {
fireError(event);
}
}, event);
if (BrowserInfo.get().isOpera()) {
// Opera onerror never fired, assume error if no onload in x
// seconds
new Timer() {
@Override
public void run() {
if (!loadedResources.contains(url)) {
fireError(event);
}
}
}.schedule(5 * 1000);
}
}
head.appendChild(linkElement);
}
}
private static native int getStyleSheetLength(String url)
/*-{
for(var i = 0; i < $doc.styleSheets.length; i++) {
if ($doc.styleSheets[i].href === url) {
var sheet = $doc.styleSheets[i];
try {
var rules = sheet.cssRules
if (rules === undefined) {
rules = sheet.rules;
}
if (rules === null) {
// Style sheet loaded, but can't access length because of XSS -> assume there's something there
return 1;
}
// Return length so we can distinguish 0 (probably 404 error) from normal case.
return rules.length;
} catch (err) {
return 1;
}
}
}
// No matching stylesheet found -> not yet loaded
return -1;
}-*/;
private static boolean addListener(String url,
ResourceLoadListener listener,
Map<String, Collection<ResourceLoadListener>> listenerMap) {
Collection<ResourceLoadListener> listeners = listenerMap.get(url);
if (listeners == null) {
listeners = new HashSet<ResourceLoader.ResourceLoadListener>();
listeners.add(listener);
listenerMap.put(url, listeners);
return true;
} else {
listeners.add(listener);
return false;
}
}
private void fireError(ResourceLoadEvent event) {
String resource = event.getResourceUrl();
Collection<ResourceLoadListener> listeners;
if (event.isPreload()) {
// Also fire error for load listeners
fireError(new ResourceLoadEvent(this, resource, false));
listeners = preloadListeners.remove(resource);
} else {
listeners = loadListeners.remove(resource);
}
if (listeners != null && !listeners.isEmpty()) {
for (ResourceLoadListener listener : listeners) {
if (listener != null) {
listener.onError(event);
}
}
}
}
private void fireLoad(ResourceLoadEvent event) {
String resource = event.getResourceUrl();
Collection<ResourceLoadListener> listeners;
if (event.isPreload()) {
preloadedResources.add(resource);
listeners = preloadListeners.remove(resource);
} else {
if (preloadListeners.containsKey(resource)) {
// Also fire preload events for potential listeners
fireLoad(new ResourceLoadEvent(this, resource, true));
}
preloadedResources.remove(resource);
loadedResources.add(resource);
listeners = loadListeners.remove(resource);
}
if (listeners != null && !listeners.isEmpty()) {
for (ResourceLoadListener listener : listeners) {
if (listener != null) {
listener.onLoad(event);
}
}
}
}
}
|