Chris Chris - 3 months ago 8
jQuery Question

How to get a list of URLs of all included/used files of webpage?

I need a way to get a list of all URLs that a website uses, includes or could use. For example the background image(es), Javascripts, css, images and so on.

Css and Javascripts would be ok for the beginning. I could get the images with parsing the DOM. But I don't know an easy way for getting all Javascript-File URLs. Or backround images that are currently not used but could be loaded via css include directions.

Is there a way to get a list of all these media with jquery or plain javascript?

Answer

Using .map( callback ) and attribute selector you can get a list of all URLs contained in a page by selecting:

$('[src], [href]')

The snippet:

$(function () {
  var importCss = $('style').text().split('\n').filter(function(element, index, array) {
    return (element.indexOf('@import') > -1) || (element.indexOf('url(') > -1);
  }).map(function(element, index, array) {
    if (element.indexOf('@import') > -1) {
      return 'Imported css: ' + element.replace(/([ ';]|@import)/g, '');
    }
    return 'Imported image: ' + element.replace(/([ ';()'"]|background-image:.*url)/g, '');
  });
  var list = $('[src], [href]').map(function(index, element) {
    return  this.tagName + ': ' + (this.src || this.href);
  }).get();

  console.log(importCss.join(',\n') + '\n'+ list.join(',\n'));

});
@import 'custom.css';
body {
  background-image: url("http://www.w3schools.com/html/pic_mountain.jpg");
}
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>


<h2>Spectacular Mountain</h2>
<img src="http://www.w3schools.com/html/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;">

<a href="http://www.w3schools.com/html/">Visit our HTML tutorial</a>