简体   繁体   中英

how to pass a parameter in the script tag in the head

I have a html page index.html . In the head tag of that page I want to define a script src:

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

I want the pId number to be filled in by the parameter I give to my html file. for example if I open .../index.html?pId=6 , I want in the script tag of that page

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

How can I do that? I tried this: Use JS variable to set the src attribute for <script> tag but the problem is that I have multiple script to load ! and nothting work anymore when I put that piece of code.

You can use this:

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

references:

Note: according to MDN URL is not supported by IE, see the link to see the browsers that support it, probably there is polyfill. currentScript is also not supported by IE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM