Select2 Pagination query optimization

I have a problem with select2 pagination. Actually, when we search something in select2. It always hit to my server and slow my processing. I want to cache my data. If i loaded first page and then click on the select2 it returns cache data instead of hit the server. For search, if i loaded first page and search something from that page then it returns the data from the cache and other wise it hits the server if data is related to another page. After that, all pages is loaded then it shouldn’t send the hit to server to load data while i loaded all pages. Is there any way to do something like that.?

I can think of two ways you could approach this:

  1. Use the Select2 ajax.transport and ajax.processResults options:

    1. Supply a transport function to check for hits in the cache and either return the cached results or make the AJAX request to the API server, and
    2. Supply a processResults function to cache the results;

    – or –

  2. Create a ServiceWorker to intercept requests to (and responses from) your API server. The ServiceWorker would need to:

    1. Cache new result pages (for a given search term), and
    2. Check for hits in the cache and either return those or allow the request to proceed to your API server.