如何在 JavaScript 中添加动态创建的脚本标签属性?

Chi*_*235 0 javascript load

我正在尝试添加data-client-key我动态创建的 JavaScript 属性。检查下面的代码我已经尝试过:

var script = document.createElement("script")
script.type = "text/javascript";
script.src = 'https://app.example.com/snap/script.js';
//script.data-client-key="CLIENT-KEY-HERE"; /* showing error message */
document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE"); /* Uncaught TypeError: Cannot read property 'setAttribute' of undefined */
document.getElementsByTagName("head")[0].appendChild(script);
Run Code Online (Sandbox Code Playgroud)

当我检查元素时,我的输出应该如下所示:

<script src="https://app.example.com/snap/script.js" data-client-key="CLIENT-KEY-HERE"></script>
Run Code Online (Sandbox Code Playgroud)

shr*_*rys 7

改变

document.getElementsByTagName(script)[0].setAttribute("data-client-key", "CLIENT-KEY-HERE");
Run Code Online (Sandbox Code Playgroud)

script.setAttribute("data-client-key", "CLIENT-KEY-HERE");
Run Code Online (Sandbox Code Playgroud)

因为您已经将脚本元素置于script变量中