prism-file-highlight.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. (function () {
  2. if (!self.Prism || !self.document || !document.querySelector) {
  3. return;
  4. }
  5. self.Prism.fileHighlight = function() {
  6. var Extensions = {
  7. 'js': 'javascript',
  8. 'html': 'markup',
  9. 'svg': 'markup',
  10. 'xml': 'markup',
  11. 'py': 'python',
  12. 'rb': 'ruby',
  13. 'ps1': 'powershell',
  14. 'psm1': 'powershell'
  15. };
  16. Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function(pre) {
  17. var src = pre.getAttribute('data-src');
  18. var extension = (src.match(/\.(\w+)$/) || [,''])[1];
  19. var language = Extensions[extension] || extension;
  20. var code = document.createElement('code');
  21. code.className = 'language-' + language;
  22. pre.textContent = '';
  23. code.textContent = 'Loading…';
  24. pre.appendChild(code);
  25. var xhr = new XMLHttpRequest();
  26. xhr.open('GET', src, true);
  27. xhr.onreadystatechange = function() {
  28. if (xhr.readyState == 4) {
  29. if (xhr.status < 400 && xhr.responseText) {
  30. code.textContent = xhr.responseText;
  31. Prism.highlightElement(code);
  32. }
  33. else if (xhr.status >= 400) {
  34. code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
  35. }
  36. else {
  37. code.textContent = '✖ Error: File does not exist or is empty';
  38. }
  39. }
  40. };
  41. xhr.send(null);
  42. });
  43. };
  44. self.Prism.fileHighlight();
  45. })();