This project provides a purely static Random Picture API. It works by generating a static site where images are renamed sequentially and a client-side JavaScript file handles the randomization logic.
- Pure Static: No backend or Edge Functions required. Deploy to GitHub Pages, Cloudflare Pages, Vercel, etc.
- Random Image Generation: Supports Horizontal (
h) and Vertical (v) images. - Session Persistence: Random images remain consistent during a user's session (until refresh or navigation away).
- Swup Integration: Automatically re-initializes when content is replaced by Swup.
- Custom Background Logic: Specifically optimized for a background element (
#bg-box) with preloading and CSS variable support. - Static Gallery: Generates a waterfall gallery page (
gallery.html) displaying all images.
- Prepare Images:
- Place horizontal images in
ri/h/. - Place vertical images in
ri/v/.
- Place horizontal images in
- Install Dependencies:
(Or just ensure you have Node.js installed; the script uses standard libraries).
npm install
- Build:
node build.js
The build script will:
- Shuffle and rename images to
1.webp,2.webp, etc. - Output everything to the
dist/folder. - Generate
dist/random.jscontaining the logic and image counts. - Generate
dist/gallery.htmlfor viewing all images.
You can configure the domain prefix (useful for CDN usage).
Set the DOMAIN environment variable before running the build.
# Example (Windows PowerShell)
$env:DOMAIN="https://your-cdn.com"; node build.jsCreate a config.json file in the root directory:
{
"domain": "https://your-cdn.com"
}Note: Environment variables take precedence over config.json.
Include the generated script in your HTML:
<script src="random.js"></script>Use a special alt attribute. The script will automatically replace the src.
<!-- For Horizontal Image -->
<img alt="random:h" title="Random Horizontal">
<!-- For Vertical Image -->
<img alt="random:v" title="Random Vertical">The script looks for an element with id="bg-box". It will:
- Fetch a random horizontal image.
- Preload it.
- Set it as
background-image. - Add the
.loadedclass to the element. - Set CSS variables
--card-bgand--float-panel-bgfor transparency effects.
<div id="bg-box"></div>For other elements, you can use the data-random-bg attribute:
<div data-random-bg="h"></div>
<div data-random-bg="v"></div>A static gallery is generated at dist/gallery.html. It displays all processed images in a responsive waterfall layout using lazy loading.
- build.js: The core build script.
- true.js: The template for the client-side logic (if used as reference).