nikolalsvk / render_async

render_async lets you include pages asynchronously with AJAX
https://rubygems.org/gems/render_async/
MIT License
1.08k stars 75 forks source link

Added lazy render #34 #84

Closed naveed-ahmad closed 5 years ago

naveed-ahmad commented 5 years ago

Added lazy rendering support using IntersectionObserver

IntersectionObserver has support for major browser, we can use polyfill for other browsers as well.

Put this in head tag if you want polufill.

  <script>
    window.IntersectionObserver || document.write('<script src="https://cdn.rawgit.com/w3c/IntersectionObserver/0cd30fe5/polyfill/intersection-observer.js"><\/script>');
  </script>

Pass lazy_load: true for lazy rendering this partial.

<%= render_async partial_path, lazy_load: true, 'data-turbolinks-track' => 'reload' do %>

Profit!

I needed this, and was surprised to see no one contributed this yet. This was quick try to see if I can develop this without using extra plugin and it works like magic :) I can clean code if core team is fine with using IntersectionObserver.

nikolalsvk commented 5 years ago

Hey @naveed-ahmad, thanks for submitting this PR! 🍰

I am so glad to see this finally! Thank you very much! Could you add examples on how to use this in the README like it's done with other features in this gem please?

nikolalsvk commented 5 years ago

Hey @naveed-ahmad, can you rebase this PR with the current master branch? I'd like to merge it in the next version of the gem 🍰

naveed-ahmad commented 5 years ago

@nikolalsvk Sorry this took some time. Instead of injecting same function in head for each call, I wanted to trigger async rendering with more dry approach. And here is the result.

Please review this repo, let me know if this approach works for this gem. I've written jquery version, can work on vanilla as well.

https://github.com/naveed-ahmad/rails_render_async/blob/master/README.md#lazy-rendering

https://github.com/naveed-ahmad/rails_render_async/blob/master/app/assets/javascripts/rails_render_async/render-async.js

IMO this approach has couple of edge cases over injecting functions:

nikolalsvk commented 5 years ago

@naveed-ahmad thanks for getting back to me. The changes you made in https://github.com/naveed-ahmad/rails_render_async/ look good, it could open up a way of doing other things to the JS part of render_async.

With separating JS logic from Rails logic, we could minify the JavaScript that's used, also apply linters and style checkers. As you said, this will give out more power if someone wanted to use render_async JS part on their own, calling it from other JavaScript code in their project.

I like where this is going! If you're interested in making a PR with these changes, I'll be more than glad to help out :)

naveed-ahmad commented 5 years ago

@nikolalsvk awesome! Closing this then, new PR is coming soon.