loadScript.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * see: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
  3. */
  4. import indexOf from 'lodash/indexOf';
  5. var gFileList = []; //list of files already added
  6. var loadjscssfile = function loadjscssfile(filename, filetype) {
  7. return new Promise(function (resolve, reject) {
  8. if (indexOf(gFileList, filename) >= 0) {
  9. console.log('loadScript: already load! ' + filename);
  10. resolve(true);
  11. return;
  12. }
  13. var fileref = null;
  14. if (filetype == 'js') {
  15. //if filename is a external JavaScript file
  16. fileref = document.createElement('script');
  17. fileref.setAttribute('type', 'text/javascript');
  18. fileref.setAttribute('src', filename);
  19. } else if (filetype == 'css') {
  20. //if filename is an external CSS file
  21. fileref = document.createElement('link');
  22. fileref.setAttribute('rel', 'stylesheet');
  23. fileref.setAttribute('type', 'text/css');
  24. fileref.setAttribute('href', filename);
  25. } else {
  26. reject(new Error('not support![' + filetype + '] ' + filename));
  27. }
  28. if (typeof fileref == 'undefined' || fileref == null) {
  29. reject(new Error('error! fileref=' + fileref));
  30. }
  31. fileref.onload = function (res) {
  32. console.log('loadScript: onload:', res);
  33. gFileList.push(filename); //List of files added in the form "[filename1],[filename2],etc"
  34. resolve(true);
  35. };
  36. fileref.onerror = function (error) {
  37. console.log('loadScript: onerror:', error);
  38. reject(new Error('load fail! ' + filename));
  39. };
  40. fileref.onabort = function (error) {
  41. console.log('loadScript: onerror:', error);
  42. reject(new Error('load abort! ' + filename));
  43. };
  44. document.getElementsByTagName('head')[0].appendChild(fileref);
  45. });
  46. };
  47. export default loadjscssfile;