Is it possible to find out how the script loaded

Suppose I have a script source.js

. There are two ways to download two:

  • <script src="source.js"></script>

  • through document.createElement

    andappendChild

Is it possible to source.js

find out from the inside about the download method?

+3


source to share


1 answer


Simple answer: No.

You can change the tag script

to an optional attribute

<script src="source.js" data-scripttag="true"></script>

Then in your file source.js

you can see if this attribute is present in the tag. If so, it is called via the script tag. However, I suppose from the question that you cannot change the HTML that calls the script (third party integration?).



This sample snippet won't work in SO, but should give an idea of ​​a way to achieve this if you can edit the HTML.

// foo.js

var scriptTags = document.querySelectorAll('[data-scripttag]');
if (scriptTags.length === 1) {
  // Called via script tag
} else {
  // injected
}
      

<script src="foo.js" data-scripttag="true"></script>

<script>
  var fs = document.getElementsByTagName('script')[0];
  var s = document.createElement('script');
  s.src = 'foo.js';
  fs.parentNode.insertBefore(s, fs)
</script>
      

Run codeHide result


0


source







All Articles