Skip to content

Commit

Permalink
feat: lazyload (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenjoezhang authored Jul 1, 2020
1 parent c742ef2 commit 8c67e6d
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ marked:
autolink: true
sanitizeUrl: false
headerIds: true
lazyload: false
prependRoot: false
external_link:
enable: false
Expand All @@ -47,6 +48,7 @@ marked:
- **autolink** - Enable autolink for URLs. E.g. `https://hexo.io` will become `<a href="https://hexo.io">https://hexo.io</a>`.
- **sanitizeUrl** - Remove URLs that start with `javascript:`, `vbscript:` and `data:`.
- **headerIds** - Insert header id, e.g. `<h1 id="value">text</h1>`. Useful for inserting anchor link to each paragraph with a heading.
- **lazyload** - Lazy loading images via `loading="lazy"` attribute.
- **prependRoot** - Prepend root value to (internal) image path.
* Example `_config.yml`:
``` yml
Expand Down
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ hexo.config.marked = Object.assign({
autolink: true,
sanitizeUrl: false,
headerIds: true,
lazyload: false,
// TODO: enable prependRoot by default in v3
prependRoot: false,
external_link: {
Expand Down
1 change: 1 addition & 0 deletions lib/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class Renderer extends MarkedRenderer {
let out = `<img src="${encodeURL(href)}"`;
if (text) out += ` alt="${text}"`;
if (title) out += ` title="${title}"`;
if (options.lazyload) out += ' loading="lazy"';

out += '>';
return out;
Expand Down
18 changes: 18 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,24 @@ describe('Marked renderer', () => {
].join('\n'));
});

it('lazyload image', () => {
const body = [
'![](/bar/baz.jpg)',
'![foo](/aaa/bbb.jpg)'
].join('\n');

ctx.config.marked.lazyload = true;

const r = require('../lib/renderer').bind(ctx);

const result = r({ text: body });

result.should.eql([
'<p><img src="/bar/baz.jpg" loading="lazy">',
'<img src="/aaa/bbb.jpg" alt="foo" loading="lazy"></p>\n'
].join('\n'));
});

describe('exec filter to extend', () => {
it('should execute filter registered to marked:renderer', () => {
const hexo = new Hexo(__dirname, {silent: true});
Expand Down

0 comments on commit 8c67e6d

Please sign in to comment.