Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for adding lazy load for images in Markdown

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.

enter image description here

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=""/>

like image 267
Arasu RRK Avatar asked Oct 20 '22 04:10

Arasu RRK


2 Answers

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.

like image 57
Leonid Shevtsov Avatar answered Nov 04 '22 02:11

Leonid Shevtsov


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.

like image 27
David Jacquel Avatar answered Nov 04 '22 02:11

David Jacquel