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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 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. }
  140. }
  141. /**
  142. * Returns the default ResourceLoader
  143. *
  144. * @return the default ResourceLoader
  145. */
  146. public static ResourceLoader get() {
  147. return INSTANCE;
  148. }
  149. /**
  150. * Load a script and notify a listener when the script is loaded. Calling
  151. * this method when the script is currently loading or already loaded
  152. * doesn't cause the script to be loaded again, but the listener will still
  153. * be notified when appropriate.
  154. *
  155. * @param scriptUrl
  156. * the url of the script to load
  157. * @param resourceLoadListener
  158. * the listener that will get notified when the script is loaded
  159. */
  160. public void loadScript(final String scriptUrl,
  161. final ResourceLoadListener resourceLoadListener) {
  162. final String url = WidgetUtil.getAbsoluteUrl(scriptUrl);
  163. ResourceLoadEvent event = new ResourceLoadEvent(this, url);
  164. if (loadedResources.contains(url)) {
  165. if (resourceLoadListener != null) {
  166. resourceLoadListener.onLoad(event);
  167. }
  168. return;
  169. }
  170. if (addListener(url, resourceLoadListener, loadListeners)) {
  171. getLogger().info("Loading script from " + url);
  172. ScriptElement scriptTag = Document.get().createScriptElement();
  173. scriptTag.setSrc(url);
  174. scriptTag.setType("text/javascript");
  175. // async=false causes script injected scripts to be executed in the
  176. // injection order. See e.g.
  177. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
  178. scriptTag.setPropertyBoolean("async", false);
  179. addOnloadHandler(scriptTag, new ResourceLoadListener() {
  180. @Override
  181. public void onLoad(ResourceLoadEvent event) {
  182. fireLoad(event);
  183. }
  184. @Override
  185. public void onError(ResourceLoadEvent event) {
  186. fireError(event);
  187. }
  188. }, event);
  189. head.appendChild(scriptTag);
  190. }
  191. }
  192. /**
  193. * Adds an onload listener to the given element, which should be a link or a
  194. * script tag. The listener is called whenever loading is complete or an
  195. * error occurred.
  196. *
  197. * @since 7.3
  198. * @param element
  199. * the element to attach a listener to
  200. * @param listener
  201. * the listener to call
  202. * @param event
  203. * the event passed to the listener
  204. */
  205. public static native void addOnloadHandler(Element element,
  206. ResourceLoadListener listener, ResourceLoadEvent event)
  207. /*-{
  208. element.onload = $entry(function() {
  209. element.onload = null;
  210. element.onerror = null;
  211. element.onreadystatechange = null;
  212. listener.@com.vaadin.client.ResourceLoader.ResourceLoadListener::onLoad(Lcom/vaadin/client/ResourceLoader$ResourceLoadEvent;)(event);
  213. });
  214. element.onerror = $entry(function() {
  215. element.onload = null;
  216. element.onerror = null;
  217. element.onreadystatechange = null;
  218. listener.@com.vaadin.client.ResourceLoader.ResourceLoadListener::onError(Lcom/vaadin/client/ResourceLoader$ResourceLoadEvent;)(event);
  219. });
  220. element.onreadystatechange = function() {
  221. if ("loaded" === element.readyState || "complete" === element.readyState ) {
  222. element.onload(arguments[0]);
  223. }
  224. };
  225. }-*/;
  226. /**
  227. * Load a stylesheet and notify a listener when the stylesheet is loaded.
  228. * Calling this method when the stylesheet is currently loading or already
  229. * loaded doesn't cause the stylesheet to be loaded again, but the listener
  230. * will still be notified when appropriate.
  231. *
  232. * @param stylesheetUrl
  233. * the url of the stylesheet to load
  234. * @param resourceLoadListener
  235. * the listener that will get notified when the stylesheet is
  236. * loaded
  237. */
  238. public void loadStylesheet(final String stylesheetUrl,
  239. final ResourceLoadListener resourceLoadListener) {
  240. final String url = WidgetUtil.getAbsoluteUrl(stylesheetUrl);
  241. final ResourceLoadEvent event = new ResourceLoadEvent(this, url);
  242. if (loadedResources.contains(url)) {
  243. if (resourceLoadListener != null) {
  244. resourceLoadListener.onLoad(event);
  245. }
  246. return;
  247. }
  248. if (addListener(url, resourceLoadListener, loadListeners)) {
  249. getLogger().info("Loading style sheet from " + url);
  250. LinkElement linkElement = Document.get().createLinkElement();
  251. linkElement.setRel("stylesheet");
  252. linkElement.setType("text/css");
  253. linkElement.setHref(url);
  254. if (BrowserInfo.get().isSafari()) {
  255. // Safari doesn't fire any events for link elements
  256. // See http://www.phpied.com/when-is-a-stylesheet-really-loaded/
  257. Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() {
  258. private final Duration duration = new Duration();
  259. @Override
  260. public boolean execute() {
  261. int styleSheetLength = getStyleSheetLength(url);
  262. if (getStyleSheetLength(url) > 0) {
  263. fireLoad(event);
  264. return false; // Stop repeating
  265. } else if (styleSheetLength == 0) {
  266. // "Loaded" empty sheet -> most likely 404 error
  267. fireError(event);
  268. return true;
  269. } else if (duration.elapsedMillis() > 60 * 1000) {
  270. fireError(event);
  271. return false;
  272. } else {
  273. return true; // Continue repeating
  274. }
  275. }
  276. }, 10);
  277. } else {
  278. addOnloadHandler(linkElement, new ResourceLoadListener() {
  279. @Override
  280. public void onLoad(ResourceLoadEvent event) {
  281. // Chrome, IE, Edge all fire load for errors, must check
  282. // stylesheet data
  283. if (BrowserInfo.get().isChrome()
  284. || BrowserInfo.get().isIE()
  285. || BrowserInfo.get().isEdge()) {
  286. int styleSheetLength = getStyleSheetLength(url);
  287. // Error if there's an empty stylesheet
  288. if (styleSheetLength == 0) {
  289. fireError(event);
  290. return;
  291. }
  292. }
  293. fireLoad(event);
  294. }
  295. @Override
  296. public void onError(ResourceLoadEvent event) {
  297. fireError(event);
  298. }
  299. }, event);
  300. if (BrowserInfo.get().isOpera()) {
  301. // Opera onerror never fired, assume error if no onload in x
  302. // seconds
  303. new Timer() {
  304. @Override
  305. public void run() {
  306. if (!loadedResources.contains(url)) {
  307. fireError(event);
  308. }
  309. }
  310. }.schedule(5 * 1000);
  311. }
  312. }
  313. head.appendChild(linkElement);
  314. }
  315. }
  316. private static native int getStyleSheetLength(String url)
  317. /*-{
  318. for(var i = 0; i < $doc.styleSheets.length; i++) {
  319. if ($doc.styleSheets[i].href === url) {
  320. var sheet = $doc.styleSheets[i];
  321. try {
  322. var rules = sheet.cssRules
  323. if (rules === undefined) {
  324. rules = sheet.rules;
  325. }
  326. if (rules === null) {
  327. // Style sheet loaded, but can't access length because of XSS -> assume there's something there
  328. return 1;
  329. }
  330. // Return length so we can distinguish 0 (probably 404 error) from normal case.
  331. return rules.length;
  332. } catch (err) {
  333. return 1;
  334. }
  335. }
  336. }
  337. // No matching stylesheet found -> not yet loaded
  338. return -1;
  339. }-*/;
  340. private static boolean addListener(String url,
  341. ResourceLoadListener listener,
  342. Map<String, Collection<ResourceLoadListener>> listenerMap) {
  343. Collection<ResourceLoadListener> listeners = listenerMap.get(url);
  344. if (listeners == null) {
  345. listeners = new HashSet<>();
  346. listeners.add(listener);
  347. listenerMap.put(url, listeners);
  348. return true;
  349. } else {
  350. listeners.add(listener);
  351. return false;
  352. }
  353. }
  354. private void fireError(ResourceLoadEvent event) {
  355. String resource = event.getResourceUrl();
  356. Collection<ResourceLoadListener> listeners = loadListeners
  357. .remove(resource);
  358. if (listeners != null && !listeners.isEmpty()) {
  359. for (ResourceLoadListener listener : listeners) {
  360. if (listener != null) {
  361. listener.onError(event);
  362. }
  363. }
  364. }
  365. }
  366. private void fireLoad(ResourceLoadEvent event) {
  367. String resource = event.getResourceUrl();
  368. Collection<ResourceLoadListener> listeners = loadListeners
  369. .remove(resource);
  370. loadedResources.add(resource);
  371. if (listeners != null && !listeners.isEmpty()) {
  372. for (ResourceLoadListener listener : listeners) {
  373. if (listener != null) {
  374. listener.onLoad(event);
  375. }
  376. }
  377. }
  378. }
  379. private static Logger getLogger() {
  380. return Logger.getLogger(ResourceLoader.class.getName());
  381. }
  382. }