如何在头部的script标签中传递参数

时间:2019-02-13 21:01:07

标签: javascript html

我有一个HTML页面index.html。我要在该页面的head tag中定义脚本src:

<script src="http://www.example/hrm.js?pId=5"></script>

我希望通过给我的html文件的参数填充pId号。 例如,如果我打开.../index.html?pId=6,我想在该页面的脚本标签中

<script src="http://www.example/hrm.js?pId=6"></script>

我该怎么做? 我尝试过:Use JS variable to set the src attribute for <script> tag 但是问题是我要加载多个脚本!当我放置那段代码时,不再工作。

1 个答案:

答案 0 :(得分:0)

您可以使用此:

var pId = new URL(document.currentScript.getAttribute('src')).searchParams.get("pId");

参考:

注意:根据IE不支持MDN URL,请查看链接以查看支持该URL的浏览器,可能是polyfill。 IE也不支持currentScript