You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResourceLoader.java 20KB

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