LoginSignup
0
0

More than 1 year has passed since last update.

jQuery を読み込まずに、$.ajax 構文だけは使えるようにするためのポリフィル

Last updated at Posted at 2022-06-11

作成したコード:

const $ = (() => {
    if (typeof jQuery === "undefined") {
        return {};
    }
    return jQuery;
})();

$.ajax =
    $.ajax ??
    (async (url, options) => {
        if (typeof url === "object") {
            options = url;
            url = undefined;
        }

        const controller = new AbortController();
        const timeoutId = window.setTimeout(
            controller.abort.bind(controller),
            options.timeout ?? 10000
        );

        const fetchOption = {
            method: options.type ?? "GET",
            cache: options.cache ? "default" : "no-cache",
            credentials: "same-origin",
            redirect: "follow",
            referrerPolicy: "no-referrer",
            signal: controller.signal,
        };

        if (options.type === "POST" && options.data !== undefined) {
            const postData = new FormData();

            Object.entries(options.data).forEach(([key, value]) => {
                if (value === undefined) {
                    return;
                }
                postData.set(key, value);
            });

            fetchOption.body = postData;
        }

        return window
            .fetch(url ?? options.url ?? "", fetchOption)
            .then((response) => {
                if (response.ok === false) {
                    console.error(response);
                    throw new Error(response.statusText);
                }
                window.clearTimeout(timeoutId);
                return response.json();
            })
            .catch((error) => {
                console.error(error);
                throw new Error(error);
            });
    });

以上のポリフィルを読み込むことで、jQuery を使わずとも、以下のような構文を利用できます。

$.ajax({
    url: "https://ajax.example.org/posts",
    type: "POST",
    cache: false,
    timeout: 5000,
    data: {
        groupID: 15,
        userID: 1992,
    }
})
    .then((result) => {
        console.log(result);
    })
    .catch((err) => {
        console.error(err);
    });

ただし、done と fail は使えません。
どう書けば使えるようになるのか見当もつきません。

// 以下は jQuery なしの場合エラーとなる。
$.ajax({
    url: "https://ajax.example.org/posts",
    type: "POST",
    cache: false,
    timeout: 5000,
    data: {
        groupID: 15,
        userID: 1992,
    }
})
    .done((result) => {
        console.log(result);
    })
    .fail((err) => {
        console.error(err);
    });

ie11 終了に伴い、jQuery を読み込まないことに決めたため、以上のポリフィルを作りました。モダンブラウザのみに対応させればよいということにしたため、fetchAPI や null 合体演算子(??)を利用しています。そのため古いブラウザでは動きません。

本当はもっと多くの引数・処理が存在するようですので、正直ポリフィルとは言えないと思います。自分が使う機能をやっつけ仕事で記述しました。もっと良い方法があったら教えてください。

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