Zend certified PHP/Magento developer

Error when configurable option dropdowns load before product gallery

I have configurable products with two different configurable attributes in my store. I have a customization in vendor/magento/module-configurable-product/view/frontend/web/js/configurable.js which automatically selects the first option in both configurable option dropdowns as soon as the page is loaded.

I’m running into a problem where sometimes only the parent product’s images display in the product’s gallery on the product detail page, and sometimes all of the images display (the configurable parent’s images plus the child simple product’s images). I’ve traced this to the fact that sometimes the gallery widget loads before the configurable widget loads, and sometimes the configurable widget loads before the gallery widget. The problem arises if the configurable widget loads before the gallery widget loads, because then the images for the configurable options haven’t been loaded when my customization automatically selects the first option in each dropdown.

The gallery widget is lib/web/mage/gallery/gallery.js

I’ve tried adding the code below to the configurable widget (in _create) to wait until the gallery gets loaded before loading the configurable widget, but this code runs forever if the configurable widget loads before the gallery widget.

var gallery = $(this.options.mediaGallerySelector)
while (!gallery.data('gallery')) {                          
    console.log("configurable._create(): waiting for data('gallery)'");
}

As far as I can tell, the gallery widget and the configurable widgets load sequentially so if I put any sort of delay in my configurable widget to wait for the gallery to get loaded, the gallery will never get loaded because its code won’t run until the configurable widget finishes.

Is there a solution to this? Is there a way to reference the configurable widget from the gallery widget, so that the last line of code in the gallery widget can set the selected options in the configurable widget?