有没有办法获取外部CSS的网址? Javascripts加载在文档的头部?
所以例如在头部:
<script type="text/javascript" src="/path/somewhere/script.js">
<link rel="stylesheet" href="/path/somewhere/styles.css">
我如何从DOM获得/path/somewhere/script.js
和/path/somewhere/styles.css
?
答案 0 :(得分:3)
只需使用querySelector
并提取相应的属性:
const script = document.querySelector('head > script');
console.log(script.src);
const css = document.querySelector('head > link');
console.log(css.href);
(由于沙盒而无法在代码段中工作)
或者,如果您需要所有脚本/ CSS网址,而不仅仅是其中一个,请循环遍历它们:
document.querySelectorAll('head > script')
.forEach(script => console.log(script.src));
document.querySelectorAll('head > link')
.forEach(css => console.log(css.href));
答案 1 :(得分:1)
<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>