可以获取< script>的查询参数. src JavaScript URL? [英] Possible to get query parameters of the <script> src JavaScript URL?
问题描述
例如,我有以下html:
As an example, I have the following html:
<body>
<script src="code.js?q=xyz"></script>
</body>
我希望能够从code.js
内部读取q=xyz
查询参数.我试过了:
I want to be able to read the q=xyz
query parameter from within code.js
. I tried:
console.log(window.location.href)
但是它给了我html文档的URL,而不是code.js
的URL(然后我可以解析该URL作为查询参数).
But it gives me the html document's URL, not code.js
's URL (I could then parse the URL for the query parameters).
是否可以从该JavaScript中获取导入的JavaScript文件的查询参数?我知道我可以读取服务器上的查询参数,然后发送回嵌入了查询参数的JavaScript,但我不希望这样做.我希望能够将JavaScript文件放在可通过查询参数进行配置的CDN上.
Is there any way to get an imported JavaScript file's query parameters from within that JavaScript? I know I could read the query parameters on a server and then send back JavaScript that has the query parameters embedded, but I don't want that. I want to be able to put JavaScript files on CDNs that can be configured via query parameters.
推荐答案
您可以使用document.currentScript.src
访问<script>
的src
属性,然后提取查询参数.对于较旧的浏览器(例如IE 11),通过以下方式访问src
-属性:
You could use document.currentScript.src
to access the <script>
's src
-attribute and then extract the query parameter. For older browsers (such as IE 11) access the src
-attribute by:
var scripts = document.getElementsByTagName('script');
var src = scripts[scripts.length - 1].src;
这将返回最后执行的脚本的src
属性.
在某些情况下,最后执行的脚本不是当前脚本(例如,如果一个脚本操纵其他<script>
元素),因此这有点不可靠.
This will return the src
-attribute of the last executed script.
In some cases the last executed script is not the current script (for example, if a script manipulates other <script>
-elements), and therefore it's a bit unreliable.
这篇关于可以获取< script>的查询参数. src JavaScript URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!