AppGeer
AppGeer

Reputation: 745

jQuery Select current script tag

Does somebody know if its possible to select the current script-tag with jQuery without any other selectordefinitions?

<script type="text/javascript">
$(document).ready( function(){
    // Here i need to select the current tag "<script ..."
})
</script>

Upvotes: 16

Views: 8434

Answers (5)

Vincent Pazeller
Vincent Pazeller

Reputation: 1498

The most robust way to achieve this is:

<script>
 (function(script){
    //do whatever you want with script here...
 })(document.currentScript);
</script>

It is more robust than other solutions because you may also use it after the document has loaded. Also it does not require the definition of a variable (if you have several script tags this might be an issue since you cannot reuse the same variable name). With JQuery:

<script>
     (function(script){
        $(document).ready(function(){
            // do whatever you want after the DOM as loaded here...
        });
     })(document.currentScript);
</script>

Upvotes: 7

Lugarini
Lugarini

Reputation: 802

try this

var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length - 1];

Upvotes: -1

Cl&#233;ssio Mendes
Cl&#233;ssio Mendes

Reputation: 1016

<script type="text/javascript">
  var currentScript = document.currentScript || (function() {
     var scripts = document.getElementsByTagName('script');
     return scripts[scripts.length - 1];
  })();
<script/>

document.currentScript works on most browsers and scripts[scripts.length - 1] is the fallback for the other ones (wich may impose some restrictions to <script async>).

Further discussion

Upvotes: 2

Sargis Markosyan
Sargis Markosyan

Reputation: 146

I think this is fastest way

<script type="text/javascript">
    var scripts = document.getElementsByTagName("script");
    var thisScript = scripts[scripts.length - 1];
</script>

Upvotes: 5

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

Outside the document ready method, just do $('script').last();:

<script type="text/javascript">
var currentScript = $('script').last();
$(document).ready( function(){
    //Use the variable currentScript here
})
</script>

Or simply give an id to your script.

Upvotes: 9

Related Questions