原方案的不足之处volantis的所有背景图都储存在配置文件中,如果图片过多,就会导致配置文件冗长
实际上,产生随机图的原理是遍历数组并随机交换,因此图片过多时加载速度也会大幅度降低
但是实际上这些图片的地址都高度相似,因此我们可以换个思路,每次生成一个随机数,并动态生成图片地址,这样就大大提高了加载速度,并且省去了填写地址的麻烦
备份在修改源码之前先备份源文件
命名格式使用数字命名图片,下标从1开始,例如 “1.jpg”,“2.jpg”.将所有图片上传至网页目录或图床中,请确保所有图片都在同一个文件夹下
修改代码
在_config.volantis.yml或volantis.yml里删除原images下的所有图片地址,改为total
1 2 3 4 5 6 7 8 parallax: enable: true position: fixed # cover: sticky on the cover. fixed: Fixed as background for the site. shuffle: true # shuffle playlist duration: 60000 # Duration (ms) fade: 1500 # fade duration (ms) (Not more than 1500) images: # For personal use only. At your own risk if used for commercial purposes !!! total: xxx
其中xxx表示图片的数量,假如你有100张图片,则total为100
打开volantis/layout/_plugins/parallax/script.ejs,如果主题更新导致文件位置改变,可以直接搜索
将代码替换为
script.ejs 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 <script> let total = <%-theme.plugins .parallax .images .total %>; let index = Math .floor (Math .random () * total) + 1 ; let IntervalParallax = null ; function parallax ( ){ let ParallaxWindow = document .querySelector ("#parallax-window" ); <% if (theme.plugins .parallax .position =="fixed" ) { %> ParallaxWindow = document .querySelector ("html" ); <% } %> Parallax .window = ParallaxWindow ; Parallax .options .fade = <%- theme.plugins .parallax .fade %>; Parallax .cache = 1 ; next_parallax (); Parallax .init (); if (total>1 ) { IntervalParallax = setInterval (function ( ) { next_parallax (); }, '<%- theme.plugins.parallax.duration %>' ); } } function next_parallax ( ) { if (typeof Parallax == "undefined" ) { return } <% if (theme.plugins .parallax .position !="fixed" ) { %> if (!document .querySelector ("#full" )&&!document .querySelector ("#half" )) { return } <% } %> if (total>=1 ) { Parallax .options .src = "你的图片地址" + index + ".jpg" ; Parallax .start (); index++; if (Parallax .cache ) { fetch ("你的图片地址" + index + ".jpg?t=" + new Date ().getTime ()); } } } var runningOnBrowser = typeof window !== "undefined" ; var isBot = runningOnBrowser && !("onscroll" in window ) || typeof navigator !== "undefined" && /(gle|ing|ro|msn)bot|crawl|spider|yand|duckgo/i .test (navigator.userAgent ); if (!isBot) { volantis.js ('<%- theme.cdn.map.js.parallax %>' ).then (()=> { parallax () }) volantis.pjax .send (()=> { clearInterval (IntervalParallax ) },"clearIntervalParallax" ); volantis.pjax .push (parallax); } </script>
将两处中文改为你的图片地址
刷新打开网页,按下CTRL+F5强制刷新,如果背景正常显示,则修改成功