5

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

Arasu RRK
  • 1,078
  • 16
  • 28
  • i think you're slightly confused about [src vs data-src](http://stackoverflow.com/a/15320346/793330). The later is just an "invisible" html container commonly used for javascript. Its not really lazy loaded. You'd still have to hook into it with some AJAX call but in that case you could easily change the src of the html. A JavaScript update of the src property is probably where the answer to your question lies. – engineerDave Aug 22 '15 at 07:00
  • @engineerDave I will use lazyload plugin to do that trick. But I didn't mentioned here... – Arasu RRK Aug 22 '15 at 09:17

2 Answers2

2

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.

Leonid Shevtsov
  • 14,024
  • 9
  • 51
  • 82
1

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.

David Jacquel
  • 51,670
  • 6
  • 121
  • 147
  • Yes. I know this syntax. But I have large amount of markdown files. I can replace the existing image syntaxes using regex. In future I'm not sure everyone in organization will follow this. So that I want to use the default syntax – Arasu RRK Aug 22 '15 at 09:23