Advantages:
Limitations:
Advantages:
Limitations:
Advantages:
Limitations:
Advantages:
Limitations:
Advantages:
Limitations:
The choice of method to reference the current script element depends on the specific requirements of the application and support for various browsers. For modern browsers, document.currentScript is the preferred approach.
","image":"http://www.luping.net/uploads/20250417/174485811168006bff0362e.jpg174485811168006bff03636.jpg","datePublished":"2025-07-22T12:36:48+08:00","dateModified":"2025-07-22T12:36:48+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}In certain scenarios, developers may need to dynamically load additional scripts into the document. However, the conventional method of using document.getElementsByTagName('head')[0].appendChild(v) may not be suitable if the HEAD element has yet to be fully rendered.
To reference the script element that loaded the currently executing script, several techniques can be employed:
Advantages:
Limitations:
<pre>
<script>
var me = document.currentScript;
</script>
</pre>
Advantages:
Limitations:
<pre>
<script>var me = document.getElementById('myscript');
</script>
</pre>
Advantages:
Limitations:
<pre>
<script data-name="myscript">
var me = document.querySelector('script[data-name="myscript"]');
</script>
</pre>
Advantages:
Limitations:
<pre>
<script src="//example.com/embed.js"></script>
</pre>
<pre>
<script>
var me = document.querySelector('script[src="//example.com/embed.js"]');
</script>
</pre>
Advantages:
Limitations:
<pre>
<script>
var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
if (isMe(scripts[i])) {
me = scripts[i];
}
}
</script>
</pre>
Advantages:
Limitations:
<pre>
<script>
var scripts = document.getElementsByTagName( 'script' );
var me = scripts[ scripts.length - 1 ];
</script>
</pre>
The choice of method to reference the current script element depends on the specific requirements of the application and support for various browsers. For modern browsers, document.currentScript is the preferred approach.
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3