您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

loadScript.native.js 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * Loads a script from a specific URL. React Native cannot load a JS
  3. * file/resource/URL via a <script> HTML element, so the implementation
  4. * fetches the specified src as plain text (e.g. via XMLHttpRequest) and then
  5. * evaluates the fetched string as JavaScript code (i.e. via the {@link eval}
  6. * function).
  7. *
  8. * @param {string} url - The absolute URL from the which the script is to be
  9. * (down)loaded.
  10. * @returns {void}
  11. */
  12. export function loadScript(url) {
  13. let fetch;
  14. const method = 'GET';
  15. // Prefer the Fetch API. Apart from the fact that we're fetching the
  16. // specified script as a static resource, the Fetch API provides more
  17. // detailed errors.
  18. if (typeof (fetch = window.fetch) === 'function') {
  19. fetch = fetch(url, { method });
  20. } else {
  21. // Otherwise, fall back to the XMLHttpRequest API.
  22. fetch
  23. = new Promise(resolve => {
  24. const xhr = new XMLHttpRequest();
  25. xhr.responseType = 'text';
  26. xhr.onreadystatechange = () => {
  27. if (xhr.readyState === 4) {
  28. resolve(xhr);
  29. }
  30. };
  31. xhr.open(method, url, /* async */ true);
  32. xhr.send();
  33. });
  34. }
  35. return (
  36. fetch
  37. .then(response => {
  38. switch (response.status) {
  39. case 200:
  40. return response.responseText || response.text();
  41. default:
  42. throw response.statusText;
  43. }
  44. })
  45. .then(responseText => {
  46. eval.call(window, responseText); // eslint-disable-line no-eval
  47. }));
  48. }