支持在Markdown中为图像添加延迟加载 [英] Support for adding lazy load for images in Markdown

查看:98
本文介绍了支持在Markdown中为图像添加延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用kramdown解析器将markdown转换为html.我想对图像使用延迟加载而不修改原始的markdown语法.我可以通过编辑kramdown gems中的link.rb文件来实现.

I'm using kramdown parser to convert markdown to html. I want to use lazy load for images without modifying original markdown syntax. I can achieve this by editing link.rb file in kramdown gems.

但是我不想遵循这种方式.因为如果有人更新kramdown,我将丢失这些编辑.还有其他方法可以在不修改原始图像语法的情况下进行此操作吗?

But I don't want to follow this way. Because if anyone updating kramdown I'll lose these edits. Is there anyother way to do this without modifying original image syntax?

原始图像语法:![](some image link)

当前输出(没有上面的编辑):<img src="some image link" alt=""/>

Current Output (without above edit): <img src="some image link" alt=""/>

预期输出:<img data-src="some image link" alt=""/>

推荐答案

您可以使用 Nokogiri 对结果HTML进行突变,这几乎就是完成任务所需的所有代码.

You can mutate the resulting HTML using Nokogiri, this is pretty much all the code you need for your task.

def responsive_img_src(html_source)
  doc = Nokogiri::HTML::Document.parse('<html></html>', nil, 'UTF-8')
  fragment = Nokogiri::HTML::DocumentFragment.new(doc, html_source)
  fragment.css('img').each { |img| img['data-src'] = img['src'] }
  return fragment.to_html
end

您不能直接使用Nokogiri::HTML(html_source)来解析您的源代码,因为它将把输出包装到格式正确的HTML文档中.这就是为什么您需要一个DocumentFragment.

You can't directly use Nokogiri::HTML(html_source) to parse your source, because it will wrap the output into a well-formed HTML document. That's why you need a DocumentFragment.

这篇关于支持在Markdown中为图像添加延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆