Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

javascript - 如何引用加载了当前正在执行的脚本的脚本标签?(How may I reference the script tag that loaded the currently-executing script?)

How can I reference the script element that loaded the javascript that is currently running?

(如何引用加载当前正在运行的javascript的脚本元素?)

Here's the situation.

(这是情况。)

I have a "master" script being loaded high in the page, first thing under the HEAD tag.

(我有一个“主”脚本被加载到页面的上方,这是HEAD标记下的第一件事。)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="scripts.js"></script>

There is a script in "scripts.js" which needs to be able to do on-demand loading of other scripts.

(“ scripts.js”中有一个脚本,该脚本需要能够按需加载其他脚本。)

The normal method doesn't quite work for me because I need to add new scripts without referencing the HEAD tag, because the HEAD element hasn't finished rendering:

(普通方法对我而言不太有效,因为我需要添加新脚本而不引用HEAD标签,因为HEAD元素尚未完成渲染:)

document.getElementsByTagName('head')[0].appendChild(v);

What I want to do is reference the script element that loaded the current script so that I can then append my new dynamically loaded script tags into the DOM after it.

(我想做的是引用加载了当前脚本的script元素,这样我就可以将新的动态加载的脚本标签附加到DOM之后。)

<script type="text/javascript" src="scripts.js"></script>
loaded by scripts.js--><script type="text/javascript" src="new_script1.js"></script>
loaded by scripts.js --><script type="text/javascript" src="new_script2.js"></script>
  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to get the current script element:(如何获取当前脚本元素:)

1. Use document.currentScript(1.使用document.currentScript)

document.currentScript will return the <script> element whose script is currently being processed.

(document.currentScript将返回当前正在处理其脚本的<script>元素。)

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

Benefits(好处)

  • Simple and explicit.

    (简单明了。)

    Reliable.

    (可靠。)

  • Don't need to modify the script tag

    (不需要修改脚本标签)

  • Works with asynchronous scripts ( defer & async )

    (与异步脚本( deferasync )一起使用)

  • Works with scripts inserted dynamically

    (与动态插入的脚本一起使用)

Problems(问题)

  • Will not work in older browsers and IE.

    (在较旧的浏览器和IE中将无法使用。)

  • Does not work with modules <script type="module">

    (不适用于模块<script type="module">)

2. Select script by id(2.按编号选择脚本)

Giving the script an id attribute will let you easily select it by id from within using document.getElementById() .

(为脚本提供id属性将使您可以轻松地使用document.getElementById()从id中选择它。)

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

Benefits(好处)

  • Simple and explicit.

    (简单明了。)

    Reliable.

    (可靠。)

  • Almost universally supported

    (几乎得到普遍支持)

  • Works with asynchronous scripts ( defer & async )

    (与异步脚本( deferasync )一起使用)

  • Works with scripts inserted dynamically

    (与动态插入的脚本一起使用)

Problems(问题)

  • Requires adding a custom attribute to the script tag

    (需要向脚本标签添加自定义属性)

  • id attribute may cause weird behaviour for scripts in some browsers for some edge cases

    (在某些情况下, id属性可能会导致某些浏览器中脚本的怪异行为)

3. Select the script using a data-* attribute(3.使用data-*属性选择脚本)

Giving the script a data-* attribute will let you easily select it from within.

(为脚本提供data-*属性将使您轻松地从内部选择它。)

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

This has few benefits over the previous option.

(与以前的选择相比,这没有什么好处。)

Benefits(好处)

  • Simple and explicit.

    (简单明了。)

  • Works with asynchronous scripts ( defer & async )

    (与异步脚本( deferasync )一起使用)

  • Works with scripts inserted dynamically

    (与动态插入的脚本一起使用)

Problems(问题)

  • Requires adding a custom attribute to the script tag

    (需要向脚本标签添加自定义属性)

  • HTML5, and querySelector() not compliant in all browsers

    (HTML5和querySelector()并非在所有浏览器中都兼容)

  • Less widely supported than using the id attribute

    (支持范围不如使用id属性)

  • Will get around <script> with id edge cases.

    (将绕过<script>id边缘情况。)

  • May get confused if another element has the same data attribute and value on the page.

    (如果另一个元素在页面上具有相同的数据属性和值,则可能会感到困惑。)

4. Select the script by src(4.通过src选择脚本)

Instead of using the data attributes, you can use the selector to choose the script by source:

(您可以使用选择器按源选择脚本,而不是使用数据属性:)

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

In embed.js:

(在embed.js中:)

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

Benefits(好处)

  • Reliable

    (可靠)

  • Works with asynchronous scripts ( defer & async )

    (与异步脚本( deferasync )一起使用)

  • Works with scripts inserted dynamically

    (与动态插入的脚本一起使用)

  • No custom attributes or id needed

    (无需自定义属性或ID)

Problems(问题)

  • Does not work for local scripts

    (不适用于本地脚本)

  • Will cause problems in different environments, like Development and Production

    (将在不同的环境中引起问题,例如开发和生产)

  • Static and fragile.

    (静态和脆弱。)

    Changing the location of the script file will require modifying the script

    (更改脚本文件的位置将需要修改脚本)

  • Less widely supported than using the id attribute

    (支持范围不如使用id属性)

  • Will cause problems if you load the same script twice

    (如果您两次加载相同的脚本,将导致问题)

5. Loop over all scripts to find the one you want(5.遍历所有脚本以查找所需的脚本)

We can also loop over every script element and check each individually to select the one we want:

(我们还可以遍历每个脚本元素,并分别检查每个脚本元素以选择所需的元素:)

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

This lets us use both previous techniques in older browsers that don't support querySelector() well with attributes.

(这使我们可以在不支持带有属性的querySelector()较旧浏览器中使用这两种先前的技术。)

For example:

(例如:)

function isMe(scriptElem){
    return scriptElem.getAttribute('src') === "//example.com/embed.js";
}

This inherits the benefits and problems of whatever approach is taken, but does not rely on querySelector() so will work in older browsers.

(这继承了采用任何方法的好处和问题,但不依赖querySelector()因此可以在较旧的浏览器中使用。)

6. Get the last executed script(6.获取最后执行的脚本)

Since the scripts are executed sequentially, the last script element will very often be the currently running script:

(由于脚本是按顺序执行的,因此最后一个脚本元素通常是当前正在运行的脚本:)

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

Benefits(好处)

  • Simple.

    (简单。)

  • Almost universally supported

    (几乎得到普遍支持)

  • No custom attributes or id needed

    (无需自定义属性或ID)

Problems(问题)

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

    (不适用于异步脚本( deferasync ))

  • Does not work with scripts inserted dynamically

    (不适用于动态插入的脚本)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...