Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to get current script element?

0 contributions
10 points

Using JavaScript it is possible to get current script element in following way.

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 new 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() {
            var date = new Date();

            return date.getTime();
        }

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

            if (script) {
                return script;
            }

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

            // script tag type is splitted because browsers secirity
          	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 new browsers.
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more