简体   繁体   中英

Create an array of all images used across a site

I want to be able to preload all images used in all pages of a website.

My idea is to create an array, containing all of these images.

What should be the best approach to this task?

For example – a naive question, probably – is there a way to use JavaScript to determine all image files used in all pages of the site within the same domain?

Or, alternatively, is there a way, for example, to create an array of all images contained in a certain folder?

Thank you in advance for your help!

In theory , you could use just JavaScript for such a thing. On page load (or document ready, or whatever), the script could:

  1. Use getElementsByTagName() to get all links on the page
  2. Do an XMLHttpRequest for the href of each same-domain link it finds.
  3. Look through each response for <img> tags, and preload each one.
  4. Look through each response for <a> tags, and repeat.

However, it'd be more efficient to maintain or generate the list of image URLs used throughout the site on the server, and include that list as a JavaScript array in the script, to avoid all the crazy AJAX image finding.

You'd want to include this script on every page on the site (as you never know what page a user will start on on your site), but save a cookie when it's run (so that it doesn't re-run on every page a given user visits).

I'd think this through carefully though. Some users could be on internet connections where their data use is limited, or charged per megabyte. Are you sure all users want to download every image on your site just from visiting one page?

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