admin管理员组

文章数量:1404612

Is there any way to get the URLs of external CSS & Javascripts loaded in the head of a document?

so for instance in head:

<script type="text/javascript" src="/path/somewhere/script.js">
<link rel="stylesheet" href="/path/somewhere/styles.css">

How would I get /path/somewhere/script.js and /path/somewhere/styles.css from DOM?

Is there any way to get the URLs of external CSS & Javascripts loaded in the head of a document?

so for instance in head:

<script type="text/javascript" src="/path/somewhere/script.js">
<link rel="stylesheet" href="/path/somewhere/styles.css">

How would I get /path/somewhere/script.js and /path/somewhere/styles.css from DOM?

Share Improve this question asked Apr 16, 2018 at 21:23 GuerrillaGuerrilla 15k37 gold badges123 silver badges241 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Just use querySelector and extract the appropriate properties:

const script = document.querySelector('head > script');
console.log(script.src);
const css = document.querySelector('head > link');
console.log(css.href);

(doesn't work in snippet due to sandboxing)

Or if you need all script/css URLs, and not just one of each, loop over them:

document.querySelectorAll('head > script')
  .forEach(script => console.log(script.src));
document.querySelectorAll('head > link')
  .forEach(css => console.log(css.href));
<script>
    let scriptTags = document.querySelectorAll('head > script');
    scriptTags.forEach(scriptTag => {
        console.log(scriptTag.getAttribute('src'));
    });

    let linkTags = document.querySelectorAll('head > link');
    linkTags.forEach(linkTag => {
        console.log(linkTag.getAttribute('href'));
    });
</script>

本文标签: javascriptGet url of scripts and styles in document headStack Overflow