Reference script container element?

别来无恙 提交于 2021-02-17 02:08:07

问题


I'm wondering if there is a way to get a handle on the DOM element that contains the script inside it. So if I had:

<script type="text/javascript> var x = ?; </script>

Is there a way that I can assign "x" a reference to the script element that contains "x"?


回答1:


You could include some marker text in the script element, and then (similar to what David said), you can loop through all the script elements in the DOM (using getElementsByTagName or whatever features your library, if you're using one, may have). That should find the element reliably. That would look something like this (live example):

<body>
  <script id='first' type='text/javascript'>
    (function() {
      var x = "MARKER:first";
    })();
  </script>
  <script id='second' type='text/javascript'>
    (function() {
      var x = "MARKER:second";
    })();
  </script>
  <script id='third' type='text/javascript'>
    (function() {
      var x = "MARKER:third";
    })();
  </script>
  <script id='last' type='text/javascript'>
    (function() {
      var scripts, index, script;

      scripts = document.getElementsByTagName("script");
      for (index = 0; index < scripts.length; ++index) {
        script = scripts[index];
        if (script.innerHTML.indexOf("MARKER:second") >= 0
           && script.id !== "last") {
          display("Found MARKER:second in script tag #" + script.id);
        }
      }

      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = msg;
        document.body.appendChild(p);
      }
    })();
  </script>
</body>

Note that, like the script above, if you're looking for a script tag marker from within a different script tag, you'll need to handle that. Above it's handled by checking the ID of the script tag, but you can also just break it up in the one you don't want to find, like this (live example):

if (script.innerHTML.indexOf("MARKER:" + "second") >= 0) {
  display("Found MARKER:" + "second in script tag #" + script.id);
}



回答2:


There isn't a truly safe way.

The closest you can come is to use getElementsByTagName to get all the scripts, get its length, get the last script element, then work from there.

This can fail if the script is deferred or if the script has been dynamically added to the page before another script element.



来源:https://stackoverflow.com/questions/3891121/reference-script-container-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!