Languages
[Edit]
EN

JavaScript - how to get current script element?

10 points
Created by:
Root-ssh
175460

In this article, we would like to show how in web browser get curreent script element reference using JavaScript.

the article presents two solutions: in-browser embedded and some legacy custom solutions.

Quick solution:

document.currentScript

or:

// ONLINE-RUNNER:browser;

<script type="text/javascript">

  console.log(document.currentScript.outerHTML);

</script>

Warning: document.currentScript appeard around 2013-2015 in major web browsers.

 

1. document.currentScript property example

This approach is not supported by all web browsers (e.g. Internet Explorer).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <script type="text/javascript">

    var script = document.currentScript;

    console.log(script.outerHTML);

  </script>
</body>
</html>

2. Custom method examples

Those approaches work with synchronous scripts in all browsers. Older browsers which do not support document.currentScript property work incorrectly with getScriptHandle() method if it is executed from asynchronous script. The method should be executed at begining of the current script to prevent situations when DOM is modified from JavaScript.

2.1. document.scripts property

Main idea of this approach is to:

  1. use document.currentScript method if it is supported,
  2. get last avaialble script element with document.scripts.
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript">
    
    function getScriptHandle() {
        var script = document.currentScript;
        if (script) {
            return script;
        } else {
            var scripts = document.scripts;
            return scripts[scripts.length - 1]
        }
    }

  </script>
</head>
<body>
  <script type="text/javascript">

    var script = getScriptHandle();
    console.log(script.outerHTML);
    
    // JavaScript code here ...

  </script>
</body>
</html>

Notes:

  • 100% support with synchronous scripts,
  • 100% support with asynchronous scripts in modern web browsers.

2.2. Script element selector

Main idea of this approach is to:

  1. use document.currentScript method if it is supported,
  2. get last avaialble script element with selector.
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript">
    
    function getScriptHandle() {
        var script = document.currentScript;
        if (script) {
            return script;
        } else {
            var scripts = document.querySelectorAll('script');
            return scripts[scripts.length - 1]
        }
    }

  </script>
</head>
<body>
  <script type="text/javascript">

    var script = getScriptHandle();
    console.log(script.outerHTML);
    
    // JavaScript code here ...

  </script>
</body>
</html>

2.3. Writing placeholder element

Main idea of this approach is to:

  1. use document.currentScript method if it is supported,
  2. create unique temporary id,
  3. use document.write() method to create temporary script element with temporary id that keeps place after current script,
  4. get handle of temporary element and move to previous element that is current script,
  5. clean up after temporary element (remove it from DOM).
// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript">

    (function() {
        var counter = 0;

        function getCounter() {
        	return ++counter;
        }
      
        function getTime() {
            return Date.now();
        }

        window.getScriptHandle = function() {
            var script = document.currentScript;

            if (script) {
                return script;
            }

            var id = 'script-placeholder-' + getCounter() + '-' + getTime();

            // script tag type is split because of browsers security
          	document.write('<s' + 'cript id="' + id + '" type="text/placeholder">' + '</s' + 'cript>');

            var placeholder = document.querySelector('#' + id);

            if (placeholder) {
                var parent = placeholder.parentNode;
                var script = placeholder.previousSibling;

                parent.removeChild(placeholder);

                if(script && script.tagName == 'SCRIPT') {
                    return script;
                }
            }

            throw new Error('Current script handle error!');
        };
    })();

  </script>
</head>
<body>
  <script type="text/javascript">

    var script = getScriptHandle();
    console.log(script.outerHTML);
    
    // JavaScript code here ...

  </script>
</body>
</html>

Notes:

  • 100% support with synchronous scripts,
  • 100% support with asynchronous scripts in modern web browsers.

Alternative titles

  1. JavaScript - how to get currently executed script element?
  2. JavaScript - document.currentScript example
  3. JavaScript - get current script handle
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join