`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module.

Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call with a dummy promise also results in the load handler being called as expected.

I'm puzzled by this behavior and wondering how to debug it.

index.html:

...
<script type="module" src="js/ui_index.js" type="javascript/module"></script>
...

(which includes an importmap for correct imports)

ui_index.js:

import * as db from "database";
...
window.addEventListener('load', () => console.log('onload'));
console.log('ui');

database.js:

import { openDB } from "lib/idb";

//         ↓↓↓↓↓ *** THIS AWAIT ***
const db = await openDB("my-database-name", 4, {

    upgrade(db, old_ver, new_ver, tx) {
        console.log(`db.upgrade ${old_ver}→${new_ver}`);
    }
}

console.log('db:', db);

The idb module used here is a promises-based IndexedDB wrapper created by Jake Archibald.

Console output with await:

db.upgrade 4→5
db: Proxy { <target>: IDBDatabase, <handler>: {…} }
ui

Console output without await:

db: Promise { <state>: "pending" }
ui
onload
db.upgrade 5→6

(The line mentioning db.upgrade only appears when incrementing the DB version in the openDB call, and does not impact the onload behavior).

Currently testing this in Firefox 120; other browsers have not been tested. This web app is intended for internal use and will be specifically designed for use with Firefox.

Answer №1

It seems that the issue might be related to where you are using the await in your script. Instead of directly awaiting a function call, try declaring a separate function that includes the await statement. This could help ensure that the onload event listener is properly attached before it is fired.

If you're open to suggestions, consider structuring your code like this:

In database.js:

import { openDB } from "lib/idb";

export default async function open() {
        const db = await openDB("my-database-name", 4, {
            upgrade(db, old_ver, new_ver, tx) {
                console.log(`db.upgrade ${old_ver}→${new_ver}`);
            }
        }
        console.log('db:', db);
}

In ui_index.js:

import open from "database";
window.addEventListener('load', () => console.log('onload'));
console.log('ui');
open();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the data from a Material UI Slider control

I'm encountering an issue with retrieving the value property I assigned to a component. event.target.value is returning undefined. How can I successfully access the value of the component? My goal is for handlePlayersChange() to be able to handle dyn ...

modifying variable values does not impact what is displayed on the screen

I'm currently facing an issue with AngularJS. I have two HTML blocks within an ng-repeat and I need to display one of them at each step. <div class="col-md-3" style="margin-top:80px" ng-init="checkFunction()"> <div id="left_group_stage"& ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

"Uncaught ReferenceError: $ is not defined - $function()" error in JavaScript/jQuery

When attempting to execute a JavaScript/jQuery function, an error is encountered when using Firebug: $ is not defined $(function()". The issue arises from the placement of the JavaScript code within a file named core.js that is referenced by index.php. W ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Error Encountered in Vue.js when Trying to Access a Nested

Below is a snippet of my route code from app.js let routes = [{ path: "/dashboard", component: require("./components/Dashboard.vue") }, { path: "/tour", component: require("./components/Index.vue"), children: [{ name: &apos ...

How to retrieve response cookies using RxJS Ajax

When using RxJS to make an Ajax call request, I am able to set the headers of the request. However, I am wondering how I can retrieve the Cookie from the RxJS Ajax Response? import { ajax } from 'rxjs/ajax'; ajax({ url: "some url", body: ...

Execute multiple JavaScript files dynamically by utilizing the same npm run command

My directory structure: app Model user.js post.js Contents of my package.json file: "scripts": { "migrate": "node ./app/Model/" } I am looking to execute JavaScript files via command line in a dynamic manner. For example: npm run migr ...

Displaying Vue.js tooltips in a table when the text gets clipped

I'm currently facing an issue with creating a tooltip in my vue.js document. I attempted to follow this guide from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_tooltip in order to create one, but it's not working as expected. Her ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

What could be causing my jQuery to only toggle the first arrow in my HTML?

I am facing an issue with a series of divs generated from data, each containing an arrow that should toggle an expandable section. Strangely, only the first div is functioning properly: toggling the arrow icon and revealing the content upon click. When th ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

I encountered an issue in reactjs where I received the error message: TypeError: this.state.coords.map is not functioning properly

Here is the code snippet I wrote: import React, { Component } from 'react'; class LocationApp extends Component { constructor(props){ super(props) this.state = { coords:[], error:[], } } ...

What is the method to verify if a variable in ES6 is constant?

I'm seeking advice on how to accomplish a specific task. I attempted using the try-catch method, but encountered some limitations: "use strict"; const a = 20; var isConst = false; try { var temp = a; a = a+1; a = temp; } catch (e) { isConst = ...

What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters? HTML <input type="number" name="cost" value= ...

Transfer information from a server to a client using the fetch API in pure JavaScript

Hey there, I've been working on a mini app that sends a fetch request to the backend and expects some information in return when a button is clicked. However, I'm facing an issue where the fetch call seems successful with a 200 status, but the d ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...