2. Script Tag ID

Advantages:

Limitations:



3. Data Attribute Selection

Advantages:

Limitations:



4. Source Selection

Advantages:

Limitations:





5. Script Iteration

Advantages:

Limitations:



6. Last Executed Script

Advantages:

Limitations:



Conclusion

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-04-22T10:00:30+08:00","dateModified":"2025-04-22T10:00:30+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
«Если рабочий хочет хорошо выполнять свою работу, он должен сначала заточить свои инструменты» — Конфуций, «Аналитики Конфуция. Лу Лингун»
титульная страница > программирование > 查找当前执行JavaScript的脚本元素方法

查找当前执行JavaScript的脚本元素方法

Опубликовано в 2025-04-22
Просматривать:664

How to Find the Script Element That Loaded the Currently Executing JavaScript?

How to Reference the Script Element That Loaded the Currently Executing Script

Understanding the Issue

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.

Solution: Referencing the Current Script

To reference the script element that loaded the currently executing script, several techniques can be employed:

1. document.currentScript

Advantages:

  • Simple, explicit, and reliable
  • Doesn't require modifying the script tag
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Limitations:

  • Not supported in older browsers or IE
  • Doesn't work with modules (<script type="module">)

<pre>
<script>
var me = document.currentScript;
</script>
</pre>

2. Script Tag ID

Advantages:

  • Simple, explicit, and reliable
  • Widely supported
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Limitations:

  • Requires adding an id attribute to the script tag

<pre>
<script>var me = document.getElementById('myscript');
</script>
</pre>

3. Data Attribute Selection

Advantages:

  • Simple and explicit
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Limitations:

  • Requires adding a custom data-* attribute to the script tag
  • Less widely supported than using ID
  • May cause confusion with other elements sharing the same data attribute

<pre>
<script data-name="myscript">
var me = document.querySelector('script[data-name="myscript"]');
</script>
</pre>

4. Source Selection

Advantages:

  • Reliable
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically
  • No custom attributes or ID required

Limitations:

  • Does not work for local scripts
  • Causes problems in different environments (e.g., dev vs. prod)
  • Static and fragile (changes to script location require modification)
  • Less widely supported than using ID
  • Problems arise if the same script is loaded multiple times

<pre>
<script src="//example.com/embed.js"></script>
</pre>

<pre>
<script>
var me = document.querySelector('script[src="//example.com/embed.js"]');
</script>
</pre>

5. Script Iteration

Advantages:

  • Inherits benefits of previous techniques
  • Doesn't rely on querySelector(), so it works in older browsers

Limitations:

  • More complex and computationally expensive

<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>

6. Last Executed Script

Advantages:

  • Simple
  • Nearly universally supported
  • No custom attributes or ID required

Limitations:

  • Does not work with asynchronous scripts (defer & async)
  • Does not work with scripts inserted dynamically

<pre>
<script>
var scripts = document.getElementsByTagName( 'script' );
var me = scripts[ scripts.length - 1 ];
</script>
</pre>

Conclusion

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