Possible to get query parameters of the <script> src JavaScript URL?

家住魔仙堡 提交于 2019-12-24 06:39:04

问题


As an example, I have the following html:

<body>
  <script src="code.js?q=xyz"></script>
</body>

I want to be able to read the q=xyz query parameter from within code.js. I tried:

console.log(window.location.href)

But it gives me the html document's URL, not code.js's URL (I could then parse the URL for the query parameters).

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.


回答1:


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;

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.



来源:https://stackoverflow.com/questions/40667307/possible-to-get-query-parameters-of-the-script-src-javascript-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!