问题
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.
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?
Original Image Syntax: ![](some image link)
Current Output (without above edit): <img src="some image link" alt=""/>
Expected Output: <img data-src="some image link" alt=""/>
回答1:
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
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.
回答2:
If you use kramdown
, you can add attributes to your markdown block. See documentation
In your case An image: ![gras](){: data-src="some image link"}
will do the trick.
来源:https://stackoverflow.com/questions/32152230/support-for-adding-lazy-load-for-images-in-markdown