async_load_css.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * 异步加载外部CSS文件,并且回调
  3. */
  4. function styleOnload(node, callback) {
  5. // for IE6-9 and Opera
  6. if (node.attachEvent) {
  7. node.attachEvent('onload', callback);
  8. // NOTICE:
  9. // 1. "onload" will be fired in IE6-9 when the file is 404, but in
  10. // this situation, Opera does nothing, so fallback to timeout.
  11. // 2. "onerror" doesn't fire in any browsers!
  12. }
  13. // polling for Firefox, Chrome, Safari
  14. else {
  15. setTimeout(function () {
  16. poll(node, callback);
  17. }, 0); // for cache
  18. }
  19. }
  20. function poll(node, callback) {
  21. if (callback.isCalled) {
  22. return;
  23. }
  24. var isLoaded = false;
  25. if (/webkit/i.test(navigator.userAgent)) {// webkit
  26. if (node['sheet']) {
  27. isLoaded = true;
  28. }
  29. }
  30. // for Firefox
  31. else if (node['sheet']) {
  32. try {
  33. if (node['sheet'].cssRules) {
  34. isLoaded = true;
  35. }
  36. } catch (ex) {
  37. // NS_ERROR_DOM_SECURITY_ERR
  38. if (ex.code === 1000) {
  39. isLoaded = true;
  40. }
  41. }
  42. }
  43. if (isLoaded) {
  44. // give time to render.
  45. setTimeout(function () {
  46. callback();
  47. }, 1);
  48. } else {
  49. setTimeout(function () {
  50. poll(node, callback);
  51. }, 1);
  52. }
  53. }
  54. // 我的动态创建LINK函数
  55. function createLink(cssURL, lnkId, charset, media) {
  56. var head = document.getElementsByTagName('head')[0], linkTag = null;
  57. if (!cssURL) {
  58. return false;
  59. }
  60. linkTag = document.createElement('link');
  61. linkTag.setAttribute('id', (lnkId || 'dynamic-style'));
  62. linkTag.setAttribute('rel', 'stylesheet');
  63. linkTag.setAttribute('charset', (charset || 'utf-8'));
  64. linkTag.setAttribute('media', (media || 'all'));
  65. linkTag.setAttribute('type', 'text/css');
  66. linkTag.href = cssURL;
  67. head.appendChild(linkTag);
  68. return linkTag;
  69. }