currentScript.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // document.currentScript polyfill by Adam Miller
  2. // MIT license
  3. (function(document){
  4. var currentScript = "currentScript",
  5. scripts = document.getElementsByTagName('script'); // Live NodeList collection
  6. // If browser needs currentScript polyfill, add get currentScript() to the document object
  7. if (!(currentScript in document)) {
  8. Object.defineProperty(document, currentScript, {
  9. get: function(){
  10. // IE 6-10 supports script readyState
  11. // IE 10+ support stack trace
  12. try { throw new Error(); }
  13. catch (err) {
  14. // Find the second match for the "at" string to get file src url from stack.
  15. // Specifically works with the format of stack traces in IE.
  16. var i, res = ((/.*at [^\(]*\((.*):.+:.+\)$/ig).exec(err.stack) || [false])[1];
  17. // For all scripts on the page, if src matches or if ready state is interactive, return the script tag
  18. for(i in scripts){
  19. if(scripts[i].src == res || scripts[i].readyState == "interactive"){
  20. return scripts[i];
  21. }
  22. }
  23. // If no match, return null
  24. return null;
  25. }
  26. }
  27. });
  28. }
  29. })(document);