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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright 2000-2016 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client;
  17. import java.util.Collection;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.Map;
  21. import java.util.Set;
  22. import java.util.logging.Logger;
  23. import com.google.gwt.core.client.Duration;
  24. import com.google.gwt.core.client.GWT;
  25. import com.google.gwt.core.client.Scheduler;
  26. import com.google.gwt.core.client.Scheduler.RepeatingCommand;
  27. import com.google.gwt.dom.client.Document;
  28. import com.google.gwt.dom.client.Element;
  29. import com.google.gwt.dom.client.LinkElement;
  30. import com.google.gwt.dom.client.NodeList;
  31. import com.google.gwt.dom.client.ScriptElement;
  32. import com.google.gwt.user.client.Timer;
  33. /**
  34. * ResourceLoader lets you dynamically include external scripts and styles on
  35. * the page and lets you know when the resource has been loaded.
  36. *
  37. * @author Vaadin Ltd
  38. * @since 7.0.0
  39. */
  40. public class ResourceLoader {
  41. /**
  42. * Event fired when a resource has been loaded.
  43. */
  44. public static class ResourceLoadEvent {
  45. private final ResourceLoader loader;
  46. private final String resourceUrl;
  47. /**
  48. * Creates a new event.
  49. *
  50. * @param loader
  51. * the resource loader that has loaded the resource
  52. * @param resourceUrl
  53. * the url of the loaded resource
  54. */
  55. public ResourceLoadEvent(ResourceLoader loader, String resourceUrl) {
  56. this.loader = loader;
  57. this.resourceUrl = resourceUrl;
  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. /**
  77. * Event listener that gets notified when a resource has been loaded.
  78. */
  79. public interface ResourceLoadListener {
  80. /**
  81. * Notifies this ResourceLoadListener that a resource has been loaded.
  82. * Some browsers do not support any way of detecting load errors. In
  83. * these cases, onLoad will be called regardless of the status.
  84. *
  85. * @see ResourceLoadEvent
  86. *
  87. * @param event
  88. * a resource load event with information about the loaded
  89. * resource
  90. */
  91. public void onLoad(ResourceLoadEvent event);
  92. /**
  93. * Notifies this ResourceLoadListener that a resource could not be
  94. * loaded, e.g. because the file could not be found or because the
  95. * server did not respond. Some browsers do not support any way of
  96. * detecting load errors. In these cases, onLoad will be called
  97. * regardless of the status.
  98. *
  99. * @see ResourceLoadEvent
  100. *
  101. * @param event
  102. * a resource load event with information about the resource
  103. * that could not be loaded.
  104. */
  105. public void onError(ResourceLoadEvent event);
  106. }
  107. private static final ResourceLoader INSTANCE = GWT
  108. .create(ResourceLoader.class);
  109. private ApplicationConnection connection;
  110. private final Set<String> loadedResources = new HashSet<>();
  111. private final Map<String, Collection<ResourceLoadListener>> loadListeners = new HashMap<>();
  112. private final Element head;
  113. /**
  114. * Creates a new resource loader. You should generally not create you own
  115. * resource loader, but instead use {@link ResourceLoader#get()} to get an
  116. * instance.
  117. */
  118. protected ResourceLoader() {
  119. Document document = Document.get();
  120. head = document.getElementsByTagName("head").getItem(0);
  121. // detect already loaded scripts, html imports and stylesheets
  122. NodeList<Element> scripts = document.getElementsByTagName("script");
  123. for (int i = 0; i < scripts.getLength(); i++) {
  124. ScriptElement element = ScriptElement.as(scripts.getItem(i));
  125. String src = element.getSrc();
  126. if (src != null && src.length() != 0) {
  127. loadedResources.add(src);
  128. }
  129. }
  130. NodeList<Element> links = document.getElementsByTagName("link");
  131. for (int i = 0; i < links.getLength(); i++) {
  132. LinkElement linkElement = LinkElement.as(links.getItem(i));
  133. String rel = linkElement.getRel();
  134. String href = linkElement.getHref();
  135. if ("stylesheet".equalsIgnoreCase(rel) && href != null
  136. && href.length() != 0) {
  137. loadedResources.add(href);
  138. }
  139. if ("import".equalsIgnoreCase(rel) && href != null
  140. && href.length() != 0) {
  141. loadedResources.add(href);
  142. }
  143. }
  144. }
  145. /**
  146. * Returns the default ResourceLoader
  147. *
  148. * @return the default ResourceLoader
  149. */
  150. public static ResourceLoader get() {
  151. return INSTANCE;
  152. }
  153. /**
  154. * Load a script and notify a listener when the script is loaded. Calling
  155. * this method when the script is currently loading or already loaded
  156. * doesn't cause the script to be loaded again, but the listener will still
  157. * be notified when appropriate.
  158. *
  159. * @param scriptUrl
  160. * the url of the script to load
  161. * @param resourceLoadListener
  162. * the listener that will get notified when the script is loaded
  163. */
  164. public void loadScript(final String scriptUrl,
  165. final ResourceLoadListener resourceLoadListener) {
  166. final String url = WidgetUtil.getAbsoluteUrl(scriptUrl);
  167. ResourceLoadEvent event = new ResourceLoadEvent(this, url);
  168. if (loadedResources.contains(url)) {
  169. if (resourceLoadListener != null) {
  170. resourceLoadListener.onLoad(event);
  171. }
  172. return;
  173. }
  174. if (addListener(url, resourceLoadListener, loadListeners)) {
  175. getLogger().info("Loading script from " + url);
  176. ScriptElement scriptTag = Document.get().createScriptElement();
  177. scriptTag.setSrc(url);
  178. scriptTag.setType("text/javascript");
  179. // async=false causes script injected scripts to be executed in the
  180. // injection order. See e.g.
  181. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
  182. scriptTag.setPropertyBoolean("async", false);
  183. addOnloadHandler(scriptTag, new ResourceLoadListener() {
  184. @Override
  185. public void onLoad(ResourceLoadEvent event) {
  186. fireLoad(event);
  187. }
  188. @Override
  189. public void onError(ResourceLoadEvent event) {
  190. fireError(event);
  191. }
  192. }, event);
  193. head.appendChild(scriptTag);
  194. }
  195. }
  196. /**
  197. * Loads an HTML import and notify a listener when the HTML import is
  198. * loaded. Calling this method when the HTML import is currently loading or
  199. * already loaded doesn't cause the HTML import to be loaded again, but the
  200. * listener will still be notified when appropriate.
  201. *
  202. * @param htmlUrl
  203. * url of HTML import to load
  204. * @param resourceLoadListener
  205. * listener to notify when the HTML import is loaded
  206. */
  207. public void loadHtmlImport(final String htmlUrl,
  208. final ResourceLoadListener resourceLoadListener) {
  209. final String url = WidgetUtil.getAbsoluteUrl(htmlUrl);
  210. ResourceLoadEvent event = new ResourceLoadEvent(this, url);
  211. if (loadedResources.contains(url)) {
  212. if (resourceLoadListener != null) {
  213. resourceLoadListener.onLoad(event);
  214. }
  215. return;
  216. }
  217. if (addListener(url, resourceLoadListener, loadListeners)) {
  218. LinkElement linkTag = Document.get().createLinkElement();
  219. linkTag.setAttribute("rel", "import");
  220. linkTag.setAttribute("href", url);
  221. addOnloadHandler(linkTag, new ResourceLoadListener() {
  222. @Override
  223. public void onLoad(ResourceLoadEvent event) {
  224. fireLoad(event);
  225. }
  226. @Override
  227. public void onError(ResourceLoadEvent event) {
  228. fireError(event);
  229. }
  230. }, event);
  231. head.appendChild(linkTag);
  232. }
  233. }
  234. /**
  235. * Adds an onload listener to the given element, which should be a link or a
  236. * script tag. The listener is called whenever loading is complete or an
  237. * error occurred.
  238. *
  239. * @since 7.3
  240. * @param element
  241. * the element to attach a listener to
  242. * @param listener
  243. * the listener to call
  244. * @param event
  245. * the event passed to the listener
  246. */
  247. public static native void addOnloadHandler(Element element,
  248. ResourceLoadListener listener, ResourceLoadEvent event)
  249. /*-{
  250. element.onload = $entry(function() {
  251. element.onload = null;
  252. element.onerror = null;
  253. element.onreadystatechange = null;
  254. listener.@com.vaadin.client.ResourceLoader.ResourceLoadListener::onLoad(Lcom/vaadin/client/ResourceLoader$ResourceLoadEvent;)(event);
  255. });
  256. element.onerror = $entry(function() {
  257. element.onload = null;
  258. element.onerror = null;
  259. element.onreadystatechange = null;
  260. listener.@com.vaadin.client.ResourceLoader.ResourceLoadListener::onError(Lcom/vaadin/client/ResourceLoader$ResourceLoadEvent;)(event);
  261. });
  262. element.onreadystatechange = function() {
  263. if ("loaded" === element.readyState || "complete" === element.readyState ) {
  264. element.onload(arguments[0]);
  265. }
  266. };
  267. }-*/;
  268. /**
  269. * Load a stylesheet and notify a listener when the stylesheet is loaded.
  270. * Calling this method when the stylesheet is currently loading or already
  271. * loaded doesn't cause the stylesheet to be loaded again, but the listener
  272. * will still be notified when appropriate.
  273. *
  274. * @param stylesheetUrl
  275. * the url of the stylesheet to load
  276. * @param resourceLoadListener
  277. * the listener that will get notified when the stylesheet is
  278. * loaded
  279. */
  280. public void loadStylesheet(final String stylesheetUrl,
  281. final ResourceLoadListener resourceLoadListener) {
  282. final String url = WidgetUtil.getAbsoluteUrl(stylesheetUrl);
  283. final ResourceLoadEvent event = new ResourceLoadEvent(this, url);
  284. if (loadedResources.contains(url)) {
  285. if (resourceLoadListener != null) {
  286. resourceLoadListener.onLoad(event);
  287. }
  288. return;
  289. }
  290. if (addListener(url, resourceLoadListener, loadListeners)) {
  291. getLogger().info("Loading style sheet from " + url);
  292. LinkElement linkElement = Document.get().createLinkElement();
  293. linkElement.setRel("stylesheet");
  294. linkElement.setType("text/css");
  295. linkElement.setHref(url);
  296. if (BrowserInfo.get().isSafari()) {
  297. // Safari doesn't fire any events for link elements
  298. // See http://www.phpied.com/when-is-a-stylesheet-really-loaded/
  299. Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
  300. private final Duration duration = new Duration();
  301. @Override
  302. public boolean execute() {
  303. int styleSheetLength = getStyleSheetLength(url);
  304. if (getStyleSheetLength(url) > 0) {
  305. fireLoad(event);
  306. return false; // Stop repeating
  307. } else if (styleSheetLength == 0) {
  308. // "Loaded" empty sheet -> most likely 404 error
  309. fireError(event);
  310. return true;
  311. } else if (duration.elapsedMillis() > 60 * 1000) {
  312. fireError(event);
  313. return false;
  314. } else {
  315. return true; // Continue repeating
  316. }
  317. }
  318. }, 10);
  319. } else {
  320. addOnloadHandler(linkElement, new ResourceLoadListener() {
  321. @Override
  322. public void onLoad(ResourceLoadEvent event) {
  323. // Chrome, IE, Edge all fire load for errors, must check
  324. // stylesheet data
  325. if (BrowserInfo.get().isChrome()
  326. || BrowserInfo.get().isIE()
  327. || BrowserInfo.get().isEdge()) {
  328. int styleSheetLength = getStyleSheetLength(url);
  329. // Error if there's an empty stylesheet
  330. if (styleSheetLength == 0) {
  331. fireError(event);
  332. return;
  333. }
  334. }
  335. fireLoad(event);
  336. }
  337. @Override
  338. public void onError(ResourceLoadEvent event) {
  339. fireError(event);
  340. }
  341. }, event);
  342. if (BrowserInfo.get().isOpera()) {
  343. // Opera onerror never fired, assume error if no onload in x
  344. // seconds
  345. new Timer() {
  346. @Override
  347. public void run() {
  348. if (!loadedResources.contains(url)) {
  349. fireError(event);
  350. }
  351. }
  352. }.schedule(5 * 1000);
  353. }
  354. }
  355. head.appendChild(linkElement);
  356. }
  357. }
  358. private static native int getStyleSheetLength(String url)
  359. /*-{
  360. for(var i = 0; i < $doc.styleSheets.length; i++) {
  361. if ($doc.styleSheets[i].href === url) {
  362. var sheet = $doc.styleSheets[i];
  363. try {
  364. var rules = sheet.cssRules
  365. if (rules === undefined) {
  366. rules = sheet.rules;
  367. }
  368. if (rules === null) {
  369. // Style sheet loaded, but can't access length because of XSS -> assume there's something there
  370. return 1;
  371. }
  372. // Return length so we can distinguish 0 (probably 404 error) from normal case.
  373. return rules.length;
  374. } catch (err) {
  375. return 1;
  376. }
  377. }
  378. }
  379. // No matching stylesheet found -> not yet loaded
  380. return -1;
  381. }-*/;
  382. private static boolean addListener(String url,
  383. ResourceLoadListener listener,
  384. Map<String, Collection<ResourceLoadListener>> listenerMap) {
  385. Collection<ResourceLoadListener> listeners = listenerMap.get(url);
  386. if (listeners == null) {
  387. listeners = new HashSet<>();
  388. listeners.add(listener);
  389. listenerMap.put(url, listeners);
  390. return true;
  391. } else {
  392. listeners.add(listener);
  393. return false;
  394. }
  395. }
  396. private void fireError(ResourceLoadEvent event) {
  397. String resource = event.getResourceUrl();
  398. Collection<ResourceLoadListener> listeners = loadListeners
  399. .remove(resource);
  400. if (listeners != null && !listeners.isEmpty()) {
  401. for (ResourceLoadListener listener : listeners) {
  402. if (listener != null) {
  403. listener.onError(event);
  404. }
  405. }
  406. }
  407. }
  408. private void fireLoad(ResourceLoadEvent event) {
  409. String resource = event.getResourceUrl();
  410. Collection<ResourceLoadListener> listeners = loadListeners
  411. .remove(resource);
  412. loadedResources.add(resource);
  413. if (listeners != null && !listeners.isEmpty()) {
  414. for (ResourceLoadListener listener : listeners) {
  415. if (listener != null) {
  416. listener.onLoad(event);
  417. }
  418. }
  419. }
  420. }
  421. private static Logger getLogger() {
  422. return Logger.getLogger(ResourceLoader.class.getName());
  423. }
  424. }