Last Updated: September 09, 2019
·
663
· yeuem1vannam

Sử dụng plugin Unveil lazy-load với Rails

Viết lại image_tag của Rails trong application_helper.rb

def image_tag(source, options = {})
  options.symbolize_keys!
  options[:src] = “#”
  src = options["data-src"] = path_to_image(source)
  unless src =~ /^(?:cid|data):/ || src.blank?
    options[:alt] = options.fetch(:alt){ image_alt(src) }
  end

  size = options.delete(:size) and if size =~ %r{^\d+x\d+$}
    options[:width], options[:height] = size.split(“x”)
  end

  if mouseover = options.delete(:mouseover)
    options[:onmouseover] = ”this.src=’#{path_to_image(mouseover)}’”
    options[:onmouseover] = ”this.src=’#{path_to_image(mouseover)}’”
  end

  tag(“img”, options)
end

Việc còn lại rất đơn giản, include Unveil vào application.js

//= require jquery.unveil

và chạy plugin

$(document).ready(function() {
    // Image lazy load plugin Unveil
    $(“img”).unveil();
});

Enjoy!

Plugin source

http://luis-almeida.github.io/unveil/

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside