0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

いいねボタンの応答速度を速く見せる方法

Posted at

初めに

いいねボタンの色変更ってそのままだと結構時間かかりますよね。
今回はjqueryを使いボタンを押した瞬間に色が変わるようにしようと思います。

like

※アニメーションはやりません。

実装

_like.html.slim
- if current_user.already_liked?(post)
  = link_to "/posts/#{post.id}/likes/#{post.likes.ids}", remote: true, method: :delete do 
    <i class="fas fa-heart unlike font-13"></i>
- else
  = link_to post_likes_path(post), remote: true, method: :post do 
    <i class="far fa-heart like font-13"></i>

span.ma-right-5
= post.likes.pluck(:id).length

普通はこうやってajaxのいいねボタンを実装すると思いますが、これだと
ボタンを押す→Likeデータ作成→create.js.erb→ボタンの色変更
という処理になります。
でもこれだとLikeデータを作成してからajaxなので更新に明らかに間ができます。

なのでボタンを押した瞬間に色を変えて、裏でlikeデータを作成するようにします。

_like.html.slim
- if current_user.already_liked?(post) 
  = link_to "/posts/#{post.id}/likes/#{post.likes.ids}", remote: true, method: :delete do 
    span.unlike
      <i class="fas fa-heart font-13"></i>
- else
  = link_to post_likes_path(post), remote: true, method: :post do 
    span.like
      <i class="far fa-heart font-13"></i>


span.ma-right-5
= post.likes.pluck(:id).length

javascript:
  $('.like').click(function() {
    $(this).delay(1).queue(function(){
      $(this).html('<i class="fas fa-heart unlike font-13"></i>');
    });
  })
  
  $('.unlike').click(function() {
    $(this).delay(1).queue(function(){
      $(this).html('<i class="far fa-heart like font-13"></i>');
    });
  })
  
  

こんな感じです。

まとめ

現在開発中のSNS、Ammotのいいねボタンがかなり遅くて悩んでいたのですが、案外簡単に解決できてよかったです。
よかったらAmmotも見てみてください。

↓トップページ:

↓僕のアカウント

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?