jQueryのfadeInが重い問題の解決法

モーダルのフェードイン処理で動作が重くなる問題にハマったので、解決方法を記録しておきます。

問題の概要

jQueryのfadeIn()メソッドを使ってモーダルを表示する際、CSSでtransitionプロパティを設定していると、アニメーションが二重に動作してしまい、パフォーマンスが悪化することがあります。

変更前のコード

JavaScript(jQuery)

$('.open-btn').on('click', function () {
    $('.modal').fadeIn().css('display', 'flex');
});
$('.close-btn').on('click', function () {
    $('.modal').fadeOut();
});

CSS

.modal {
    position: fixed;
    width: 100vw;
    height: 100svh;
    z-index: 999999;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: scroll;
    display: none;
    background: black;
    transition: .3s; /* ←この行が問題 */
}

問題の原因

上記のコードでは以下の問題が発生していました:

  • アニメーションの競合: jQueryのfadeIn()とCSSのtransitionが同時に動作
  • パフォーマンス低下: 二重のアニメーション処理による負荷増加
  • 予期しない動作: 意図しないアニメーション効果の発生

解決方法

CSSのtransitionプロパティを削除するだけで解決できます。

変更後のCSS

.modal {
    position: fixed;
    width: 100vw;
    height: 100svh;
    z-index: 999999;
    left: 0;
    top: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: scroll;
    display: none;
    background: black;
    /* transition: .3s; ←この行を削除 */
}

JavaScript(jQuery)

// 変更なし
$('.open-btn').on('click', function () {
    $('.modal').fadeIn().css('display', 'flex');
});
$('.close-btn').on('click', function () {
    $('.modal').fadeOut();
});

まとめ

jQueryのアニメーションメソッドを使用する際は、CSSのtransitionプロパティとの競合に注意が必要です。シンプルな解決策として、不要なtransitionを削除するだけで大幅にパフォーマンスが改善されることがあります。