browser.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var utils = require('./utils');
  2. module.exports = {
  3. createCSS: function (document, styles, sheet) {
  4. // Strip the query-string
  5. var href = sheet.href || '';
  6. // If there is no title set, use the filename, minus the extension
  7. var id = 'less:' + (sheet.title || utils.extractId(href));
  8. // If this has already been inserted into the DOM, we may need to replace it
  9. var oldStyleNode = document.getElementById(id);
  10. var keepOldStyleNode = false;
  11. // Create a new stylesheet node for insertion or (if necessary) replacement
  12. var styleNode = document.createElement('style');
  13. styleNode.setAttribute('type', 'text/css');
  14. if (sheet.media) {
  15. styleNode.setAttribute('media', sheet.media);
  16. }
  17. styleNode.id = id;
  18. if (!styleNode.styleSheet) {
  19. styleNode.appendChild(document.createTextNode(styles));
  20. // If new contents match contents of oldStyleNode, don't replace oldStyleNode
  21. keepOldStyleNode = (oldStyleNode !== null && oldStyleNode.childNodes.length > 0 && styleNode.childNodes.length > 0 &&
  22. oldStyleNode.firstChild.nodeValue === styleNode.firstChild.nodeValue);
  23. }
  24. var head = document.getElementsByTagName('head')[0];
  25. // If there is no oldStyleNode, just append; otherwise, only append if we need
  26. // to replace oldStyleNode with an updated stylesheet
  27. if (oldStyleNode === null || keepOldStyleNode === false) {
  28. var nextEl = sheet && sheet.nextSibling || null;
  29. if (nextEl) {
  30. nextEl.parentNode.insertBefore(styleNode, nextEl);
  31. } else {
  32. head.appendChild(styleNode);
  33. }
  34. }
  35. if (oldStyleNode && keepOldStyleNode === false) {
  36. oldStyleNode.parentNode.removeChild(oldStyleNode);
  37. }
  38. // For IE.
  39. // This needs to happen *after* the style element is added to the DOM, otherwise IE 7 and 8 may crash.
  40. // See http://social.msdn.microsoft.com/Forums/en-US/7e081b65-878a-4c22-8e68-c10d39c2ed32/internet-explorer-crashes-appending-style-element-to-head
  41. if (styleNode.styleSheet) {
  42. try {
  43. styleNode.styleSheet.cssText = styles;
  44. } catch (e) {
  45. throw new Error('Couldn\'t reassign styleSheet.cssText.');
  46. }
  47. }
  48. },
  49. currentScript: function(window) {
  50. var document = window.document;
  51. return document.currentScript || (function() {
  52. var scripts = document.getElementsByTagName('script');
  53. return scripts[scripts.length - 1];
  54. })();
  55. }
  56. };