Wix

Mastering Dynamic Image Layouts in Wix Pro Gallery: A Developer's Guide

For e-commerce store owners and developers seeking to integrate external media seamlessly into their Wix websites, the Wix Pro Gallery offers powerful customization options. However, a common challenge arises when attempting to programmatically populate a Pro Gallery with external images, especially when aiming for advanced layouts like Masonry. While the Pro Gallery excels at dynamic resizing and arrangement for images uploaded directly through the Wix editor, integrating custom JavaScript to fetch images from an external server can sometimes disrupt this sophisticated layout engine, leading to unexpected cropping instead of intelligent resizing. This guide will walk you through the nuances of programmatic image loading in Wix Pro Gallery and provide actionable solutions to ensure your dynamic layouts function as intended.

Comparison of cropped grid layout vs. adaptive Masonry layout in Wix Pro Gallery
Comparison of cropped grid layout vs. adaptive Masonry layout in Wix Pro Gallery

The Core Challenge: Programmatic vs. Editor-Loaded Content

The issue typically manifests when a store owner uses custom Velo (Wix's development platform) code to fetch image URLs from their own server and assign them to a Pro Gallery component. Despite configuring the gallery for a 'Custom' Masonry layout with specific settings (e.g., vertical layout, items per row, spacing), the images appear in a rigid grid. Instead of adapting to varying aspect ratios, the gallery crops images to fit a uniform size, negating the very purpose of a Masonry layout.

This discrepancy highlights a crucial difference in how the Wix Pro Gallery processes content:

  • Editor-Loaded Images: When images are uploaded via the Wix editor, the platform's internal mechanisms likely pre-process each image. This includes extracting critical metadata such as natural width and height, which are then stored and used by the gallery's layout engine to calculate optimal placement and resizing for dynamic layouts like Masonry.
  • Programmatically Loaded Images: When images are loaded via custom JavaScript, the gallery component receives only the basic properties provided in the items array, typically type and src. Without explicit width and height properties for each image, the Pro Gallery's layout engine lacks the essential information needed to correctly calculate aspect ratios and apply sophisticated layouts like Masonry. It defaults to a simpler, often uniform, grid-like arrangement, leading to undesirable cropping.

Understanding the Masonry Layout Imperative

A Masonry layout is designed to display items of varying heights and widths in a visually appealing, gap-free grid. Think of a brick wall, where bricks of different sizes fit together perfectly. For this to work, the layout engine needs to know the dimensions of each 'brick' (image) to calculate how it will fit into the available space. When you assign an image to the Pro Gallery programmatically using only its URL (src), the gallery doesn't automatically know its intrinsic dimensions. It then makes assumptions, often defaulting to a square or a fixed aspect ratio, which results in cropping when images don't conform to that assumption.

The Missing Pieces: Width and Height

The solution lies in providing the Pro Gallery with the necessary metadata: the natural width and height of each image. The items array for a Wix Pro Gallery can accept these properties. When you fetch image URLs from your server, your custom code needs to also either retrieve or dynamically determine these dimensions before populating the gallery.

Strategies for Obtaining Image Dimensions

There are two primary approaches to ensure your programmatically loaded images include their dimensions:

1. Server-Side Pre-processing (Recommended for Performance)

The most efficient method is to store the width and height of your images alongside their URLs in your server's database or API response. When your custom function fetches image data, it should return not just the URL, but also the dimensions. This offloads the dimension calculation from the client-side, leading to faster page loads and a smoother user experience.

// Example of server response (getMedia() function) 
let mediaData = [
  { url: "image1.jpg", type: "image", width: 1200, height: 800 },
  { url: "image2.png", type: "image", width: 600, height: 900 },
  { url: "video1.mp4", type: "video", width: 1920, height: 1080 }
];

2. Client-Side Dynamic Dimension Fetching

If server-side pre-processing isn't feasible, you can dynamically fetch image dimensions on the client-side using JavaScript. This involves creating a temporary Image object, setting its src, and waiting for it to load to retrieve its naturalWidth and naturalHeight. While effective, this method introduces a slight delay as each image needs to load (at least partially) to get its dimensions before the gallery can be fully rendered.

$w.onReady(function () {
  getMedia() // Your custom function to get media URLs
    .then(async (mediaUrls) => {
      console.log(mediaUrls);
      let baseUrl = "fakewebsite.com"; // Replace with your actual base URL
      let items = [];

      for (const mediaUrl of mediaUrls) {
        const fullUrl = baseUrl + "/" + mediaUrl;
        let item = {
          type: mediaUrl.includes("mp4") || mediaUrl.includes("mov") ? "video" : "image",
          src: fullUrl
        };

        if (item.type === "image") {
          await new Promise((resolve) => {
            const img = new Image();
            img. => {
              item.width = img.naturalWidth;
              item.height = img.naturalHeight;
              resolve();
            };
            img. => {
              console.error("Failed to load image for dimensions: " + fullUrl);
              resolve(); // Resolve even on error to prevent blocking
            };
            img.src = fullUrl;
          });
        }
        items.push(item);
      }
      $w('#gallery3').items = items; // Assign the prepared items array to your gallery
    })
    .catch((err) => {
      console.error(err);
    });
});

Note: For video items, you would typically rely on server-side stored dimensions or a default aspect ratio, as dynamically fetching video dimensions client-side is more complex and resource-intensive.

Implementing the Solution in Your Velo Code

Once you have the width and height for each image, you simply include them in the items array you assign to your Pro Gallery. The gallery's layout engine will then have all the information it needs to correctly apply your chosen Masonry layout.

Here's how the updated structure for an image item would look:

{
  type: "image",
  src: "https://fakewebsite.com/image-path.jpg",
  width: 1200, // Natural width of the image
  height: 800  // Natural height of the image
}

By populating the items array with these crucial width and height properties, you empower the Wix Pro Gallery to execute its sophisticated Masonry layout algorithms, ensuring your images are displayed beautifully and without unwanted cropping, regardless of their aspect ratio.

Best Practices for E-commerce Galleries

For e-commerce sites, visually appealing product galleries are paramount. Implementing these solutions ensures:

  • Enhanced User Experience: Products are displayed optimally, allowing customers to fully appreciate details without awkward cropping.
  • Improved Aesthetics: A well-executed Masonry layout creates a modern, professional look for your store.
  • Consistency Across Platforms: Whether you're displaying images from your own CDN or a third-party asset manager, maintaining layout integrity is key.
  • SEO Benefits: Faster loading galleries (especially with server-side dimension pre-processing) contribute to better page speed, a factor in search engine rankings.

Conclusion

Integrating external media into your Wix Pro Gallery with custom Velo code opens up a world of possibilities for dynamic content. While the initial challenge of maintaining advanced layouts like Masonry might seem daunting, understanding the gallery's reliance on image dimensions is the key. By proactively providing the width and height properties for your programmatically loaded images, whether through server-side optimization or client-side fetching, you can unlock the full potential of the Wix Pro Gallery, delivering a seamless and visually stunning experience for your e-commerce customers. This attention to detail transforms a basic image grid into a sophisticated, adaptive display, elevating your site's professional appeal and user engagement.

Share: