asset_loader.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const assetLoader = (function () {
  2. function formatResponse(xhr) {
  3. // using typeof doubles the time of execution of this method,
  4. // so if available, it's better to use the header to validate the type
  5. var contentTypeHeader = xhr.getResponseHeader('content-type');
  6. if (contentTypeHeader && xhr.responseType === 'json' && contentTypeHeader.indexOf('json') !== -1) {
  7. return xhr.response;
  8. }
  9. if (xhr.response && typeof xhr.response === 'object') {
  10. return xhr.response;
  11. } if (xhr.response && typeof xhr.response === 'string') {
  12. return JSON.parse(xhr.response);
  13. } if (xhr.responseText) {
  14. return JSON.parse(xhr.responseText);
  15. }
  16. return null;
  17. }
  18. function loadAsset(path, callback, errorCallback) {
  19. var response;
  20. var xhr = new XMLHttpRequest();
  21. // set responseType after calling open or IE will break.
  22. try {
  23. // This crashes on Android WebView prior to KitKat
  24. xhr.responseType = 'json';
  25. } catch (err) {} // eslint-disable-line no-empty
  26. xhr.onreadystatechange = function () {
  27. if (xhr.readyState === 4) {
  28. if (xhr.status === 200) {
  29. response = formatResponse(xhr);
  30. callback(response);
  31. } else {
  32. try {
  33. response = formatResponse(xhr);
  34. callback(response);
  35. } catch (err) {
  36. if (errorCallback) {
  37. errorCallback(err);
  38. }
  39. }
  40. }
  41. }
  42. };
  43. // Hack to workaround banner validation
  44. xhr.open(['G', 'E', 'T'].join(''), path, true);
  45. xhr.send();
  46. }
  47. return {
  48. load: loadAsset,
  49. };
  50. }());
  51. export default assetLoader;