Skip to content

Commit

Permalink
feat: Added support for inline currentScript calls in IE and Edge (#5)
Browse files Browse the repository at this point in the history
  - Fixed a few linting issues
  - Reworked performance-relevant parts of the code
  - Added .editorconfig
  • Loading branch information
Schepp authored and amiller-gh committed Dec 17, 2019
1 parent c7c4211 commit e1f8227
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
@@ -0,0 +1,3 @@
[*]
indent_style = space
indent_size = 2
53 changes: 40 additions & 13 deletions currentScript.js
Expand Up @@ -2,27 +2,54 @@

// MIT license

(function(document){
var currentScript = "currentScript",
scripts = document.getElementsByTagName('script'); // Live NodeList collection
(function (document) {
var currentScript = 'currentScript';

// If browser needs currentScript polyfill, add get currentScript() to the document object
if (!(currentScript in document)) {
Object.defineProperty(document, currentScript, {
get: function(){

// IE 6-10 supports script readyState
// IE 10+ support stack trace
try { throw new Error(); }
get: function () {
// IE 8-10 support script readyState
// IE 11+ support stack trace
try {
throw new Error();
}
catch (err) {

// Find the second match for the "at" string to get file src url from stack.
// Specifically works with the format of stack traces in IE.
var i, res = ((/.*at [^\(]*\((.*):.+:.+\)$/ig).exec(err.stack) || [false])[1];
var i = 0,
stackDetails = (/.*at [^(]*\((.*):(.+):(.+)\)$/ig).exec(err.stack),
scriptLocation = (stackDetails && stackDetails[1]) || false,
line = (stackDetails && stackDetails[2]) || false,
currentLocation = document.location.href.replace(document.location.hash, ''),
pageSource,
inlineScriptSourceRegExp,
inlineScriptSource,
scripts = document.getElementsByTagName('script'); // Live NodeList collection

if (scriptLocation === currentLocation) {
pageSource = document.documentElement.outerHTML;
inlineScriptSourceRegExp = new RegExp('(?:[^\\n]+?\\n){0,' + (line - 2) + '}[^<]*<script>([\\d\\D]*?)<\\/script>[\\d\\D]*', 'i');
inlineScriptSource = pageSource.replace(inlineScriptSourceRegExp, '$1').trim();
}

for (; i < scripts.length; i++) {
// If ready state is interactive, return the script tag
if (scripts[i].readyState === 'interactive') {
return scripts[i];
}

// If src matches, return the script tag
if (scripts[i].src === scriptLocation) {
return scripts[i];
}

// For all scripts on the page, if src matches or if ready state is interactive, return the script tag
for(i in scripts){
if(scripts[i].src == res || scripts[i].readyState == "interactive"){
// If inline source matches, return the script tag
if (
scriptLocation === currentLocation &&
scripts[i].innerHTML &&
scripts[i].innerHTML.trim() === inlineScriptSource
) {
return scripts[i];
}
}
Expand Down

0 comments on commit e1f8227

Please sign in to comment.