hexo-theme-keep/scripts/filters/lazyload-handle.js

32 lines
828 B
JavaScript
Raw Normal View History

2022-10-04 23:52:46 +08:00
/* global hexo */
2021-01-07 15:15:39 +08:00
'use strict'
2022-10-04 23:52:46 +08:00
2021-01-07 15:15:39 +08:00
hexo.extend.filter.register(
'after_post_render',
function (data) {
const theme = hexo.theme.config
if (!theme.lazyload || !theme.lazyload.enable) return
2021-01-07 15:15:39 +08:00
data.content = data.content.replace(
2022-10-04 23:52:46 +08:00
// Match 'img' tags the src attribute.
2021-04-27 15:11:41 +08:00
/<img([^>]*)src="([^"]*)"([^>\/]*)\/?\s*>/gim,
2021-01-07 15:15:39 +08:00
function (match, attrBegin, src, attrEnd) {
let hasAlt = false
if (!src) return match
if (attrBegin.includes('alt="')) {
hasAlt = true
} else if (attrBegin.includes('alt="')) {
hasAlt = true
}
2021-01-07 15:15:39 +08:00
return `<img ${attrBegin}
lazyload
${hasAlt ? '' : 'alt="image"'}
2021-01-07 15:15:39 +08:00
data-src="${src}"
${attrEnd}
>`
}
)
},
1
)