Dynamic Item Page Gallery Not Always Working

Hello!

I have a gallery on a dynamic item page that is being populated through code. wThe gallery is hidden and collapsed on page load and then if there are images that correlate with that item the gallery is populated through code and then expanded and shown. Sometimes when I preview the page the gallery shows up and other times it does not (the space where the gallery would be is visible but the images are not).

Here is the code:

let photos = [];
let videos = [];
let gallery = [];
    $w("#pictures").onReady(() => {
        $w("#pictures").getItems(0, 20).then((result) => {
                photos = result.items;
 for (var photo in photos) {
 if (photos[photo]["video_url"]) {
                        videos.push(photos[photo]);
                    } else {
 let item = {};
                        item.src = photos[photo]["image"];
                        item.title = photos[photo]["title"];
                        gallery.push(item);
                    }
                }
 if (videos.length > 0) {
                    $w("#video1").videoUrl = videos[0]["video_url"];
                    $w("#columnStrip9").show();
                    $w("#columnStrip9").expand();
                }

 if (gallery.length > 0) {
                    $w("#gallery1").items = gallery;
                    $w("#columnStrip8").show();
                    $w("#columnStrip8").expand();
                }
            })
            .catch((err) => {
 let errMsg = err.message;
 let errCode = err.code;
            });
    });

First of all, can you please share your website url?
I can suggest trying to put this code in the onready function
$w.onReady( async function () { CODE_GOES_HERE })