Click listener with sql query takes a long time to run the first time

57 views Asked by At

I've the following html where I'm loading a local SQLite database (~3MB), and there's a button with a click event listener that executes an SQL query and logs the results.

<!DOCTYPE html>

<body>
    <button id='btn'>GO</button>

    <script src='https://cdnjs.cloudflare.com/ajax/libs/sql.js/0.3.2/js/sql.js'></script>

    <script>
        (async () => {
            const response = await fetch('data.db')
            const buffer = await response.arrayBuffer()
            const db = new SQL.Database(new Uint8Array(buffer))

            console.log('Db loaded')

            const btn = document.getElementById('btn')

            btn.addEventListener('click', async () => {
                 //console.time("query_execution_time");
                const query = 'select * from tb';
                const result = db.exec(query)[0].values;
                console.log(result);
                //console.timeEnd("query_execution_time");
            });
        })()
    </script>

</body>

</html>

The first time the button is clicked (after the database is loaded), there is a noticeable delay (~1000ms) before the results are logged.

However, subsequent clicks on the button happen almost instantaneously (50-100ms).

What am I doing wrong?

(Note that the delay is not due to the database loading process itself, as that occurs before the click event listener is attached to the button.)

1

There are 1 answers

0
Shub On

Using a prepare statement might help after the database is initialized:

db.prepare('select * from tb')