Languages
[Edit]
EN

JavaScript - how to get current script element?

10 points
Created by:
Root-ssh
68500

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

Quick solution:

<script type="text/javascript">
  console.log(document.currentScript.outerHTML);
</script>

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.
Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join