Serve modern-format Images from Squarespace with Imagekit
Imagekit is a Digital Asset Management (DAM) platform that helps deliver images through their global CDN. Similar to Cloudinary or Cloudimage, Imagekit supports serving remote files from the Squarespace CDN and WebP conversion out of the box. This makes it an excellent choice for serving next-gen image formats on Squarespace websites.
In this post, we’ll explore an alternative approach to caching and delivering Squarespace images using Imagekit. This assumes you are already familiar with Squarespace's responsive images and the reasons behind using this technique as well as the known limitations.
The code will be provided at the end of the article.
Getting started with Imagekit
Imagekit comes with a free generous plan, so you can get 25GB monthly bandwidth for free, first let’s register an account there
Step 1: Configure Origin
To use Imagekit, you need an image source where the images come from. You can either upload images directly to Imagekit or use remote image files. Since our images are stored on Squarespace, we'll create a Web Server image origin.
Go to the External Storage section in your Imagekit.io dashboard, and click the "Add New" button.
Choose "Web Folder" from the Origin type dropdown.
Give your origin a name, such as "Squarespace CDN".
Fill out the base URL with
https://images.squarespace-cdn.com/
.Leave the advanced options as they are for now.
Click the Save button.
Step 2: Access the File Through Imagekit.io URL Endpoint
When you add your first external source (origin) in the dashboard, it becomes accessible through the default URL endpoint of your Imagekit.io account. For subsequent origins, you can either create a separate URL endpoint or edit the existing URL endpoint (including default) and make the new origin accessible by editing the origin preference list.
Go to the URL Endpoints section in your Imagekit.io dashboard and click the Default URL endpoint or Add New to create a new endpoint.
In the Image Origin Preference section, click the Attach an Existing Origin button and choose the Squarespace CDN origin you just created.
Copy and save the URL endpoint identifier.
For example, if you request:
https://ik.imagekit.io/<your_imagekit_id>/content/615d0bdeb9e47e1e585827d3/1721567832031-9CJ5GUY96NE85IVB19CM/cloudinary_no_f_auto.png
ImageKit.io internally fetches the file from
https://images.squarespace-cdn.com/content/615d0bdeb9e47e1e585827d3/1721567832031-9CJ5GUY96NE85IVB19CM/cloudinary_no_f_auto.png
By default, Imagekit will automatically convert and deliver your images in WebP format to supported browsers, with the quality set at 80%. If you need to change this setting, go to the Imagekit dashboard and follow the instructions to adjust the default settings.
The image on the WebP Imagekit CDN will be delivered in WebP format if supported, with the image below file size is reduced by 70% compared to the JPG version (115 kB vs 291 kB).
Cloudinary vs. ImageKit: free plan comparison
Cloudinary and ImageKit both offer valuable resources in their free plans, but they cater to different needs.
Cloudinary provides 25 units per month, meaning 25k monthly transformations OR 25GB of managed storage OR 25GB of monthly net viewing bandwidth. This makes it a comprehensive solution for those who require extensive image and video transformations.
On the other hand, ImageKit includes 25GB of media delivery bandwidth, 5GB of DAM storage, and 500 video processing units. It allows for unlimited master images and image transformations, supports three users, and provides 650 extension units for operations in the DAM. ImageKit stands out with its detailed analytics, offering clearer insights into your usage compared to Cloudinary's reporting.
Moreover, ImageKit supports smart cropping for all COCO
classes objects out of the box. In comparison, Cloudinary's default object detection focuses on faces and general auto-detection. If you need to target a specific object, Cloudinary offers the AI Content Analysis add-on, allowing you to specify the object as the gravity point with 500 free credits per month. This makes ImageKit an affordable option for smart cropping.
In summary, Cloudinary excels in its powerful image and video transformation capabilities, making it suitable for more complex needs. However, for serving Squarespace images, ImageKit is advantageous because the delivered images do not count toward storage limits. Despite having fewer video transformation credits, ImageKit's analytics are more detailed and user-friendly, making it a better choice for managing your image delivery and optimization.
Solution
The solution involves replacing the srcset
attributes of image elements with Imagekit URL endpoint. Depending on user preferences, you can either fetch only the largest variant as the master Image and use Imagekit’s resizing transformations for the other variants (100, 300, 500, 750, 1000, 1500, 2500) or use Squarespace image variants directly without escaping URL parameters.
Testing
By injecting the script into the Footer injection, you can observe the difference in image requests (notice the transferred size) in the Chrome Network tab. Most images will be served as WebP on supported browsers like Chrome and the total resources size is reduced
Default | Using ImageKit | |
---|---|---|
Total Images | 28 | 28 |
Webp Ratio | 0 / 28 | 25 / 28 |
Resource Size | 11 MB | 6.5 MB |
Why not all images are delivered as Webp?
This is the inherent issue with a JavaScript solution. Although the code is placed inside the `DOMContentLoaded` event, image loading in the browser is a race. There is no practical method fast enough to replace all images upon page load.
The Code
To get started, you'll need to customize a few variables in the provided code snippet. Here’s how you can do it:
1. Imagekit URL Endpoint (required)
Replace "imagekit-endpoint"
with your actual Imagekit endpoint.
const IMAGEKIT_URL_ENDPOINT = "imagekit-endpoint";
2. Transformations
Specify the transformations you want to apply. For more details, check out Imagekit’s Image Transformations documentation. Notes: remove the prefix tr: as it is already included in the code
const IMAGEKIT_TRANSFORMATIONS = "" // eg: f-auto,q-auto, seperate transformations by comma
3. Image Variants
Determine whether to use Squarespace's image variants or let Imagekit handle resizing. If true
, the code will use Squarespace’s variants. Set to false
to use Imagekit resizing parameters instead.
const USE_SQUARESPACE_VARIANTS = true;
4. Variant Size Limit
Set the maximum size for the image variants. This controls the maximum variant to be used within body width, as explain in the previous post. Options available are 100, 300, 500, 750, 1500, or 2500.
const LIMIT_VARIANT_SIZE = 1500;
5. Excluded Images
If you want to exclude certain images (like fullscreen banners or lightbox images), list their selectors here. This ensures that high-quality images are preserved where needed.
const EXCLUDED_IMAGES = [];
To activate the code on your site:
Copy the code snippet below
Paste them in your Footer code injection
Edit the parameters as suggested above, especially setting actual Imagekit endpoint.
Save the change
<!-- sqs:image-loader-helper --> <script> window.ImageLoaderInterceptor = window.ImageLoaderInterceptor || (function () { // Check if the script has already been executed if (window.ImageLoaderInterceptorExecuted) return; window.ImageLoaderInterceptorExecuted = true; document.addEventListener('DOMContentLoaded', function () { const IMAGEKIT_URL_ENDPOINT = "imagekit-endpoint"; const IMAGEKIT_TRANSFORMATIONS = "" // eg: f-auto,q-auto, seperate transformations by comma const USE_SQUARESPACE_VARIANTS = true; // Use Squarespace variant via ?format={variant}, set fale will use Imagekit transformation params instead const LIMIT_VARIANT_SIZE = 1500; // Save a list of images container to be excluded const EXCLUDED_IMAGES = [ ".section-background", ".gallery-fullscreen-slideshow-item", ".gallery-lightbox-outer-wrapper", ".yui3-lightbox2 .sqs-lightbox-slideshow" ]; const validImageSelector = EXCLUDED_IMAGES.map(selector => `${selector} img`).join(', '); const validImages = document.querySelectorAll(`img[data-src]:not(${validImageSelector})`); Array.from(validImages).forEach((image) => { const src = image.dataset.src; let overrideDatasrc = ''; const sizes = [100, 300, 500, 750, 1000, 1500, 2500]; let srcSets = sizes.map(size => { // Limit the size to 1500, skip the 2500 variant const actualSize = size === 2500 ? LIMIT_VARIANT_SIZE : size; if (!IMAGEKIT_URL_ENDPOINT) { return `${src}?format=${actualSize}w`; } else { let _src = src.replace("https://images.squarespace-cdn.com/", ""); let transformations = IMAGEKIT_TRANSFORMATIONS.split(',').filter(Boolean); transformations.push(`sqspcdn.com-true`); if (!overrideDatasrc && size === 2500) { overrideDatasrc = `${IMAGEKIT_URL_ENDPOINT}${transformations.length ? `tr:${transformations.join(',')}` : ''}/${_src}`; } if (USE_SQUARESPACE_VARIANTS) { return `${IMAGEKIT_URL_ENDPOINT}${_src}?format=${actualSize}w&${transformations.length ? `tr=${transformations.join(',')}` : ''}`; } else { transformations.push(`w-${actualSize}`); transformations.push(`c-at_max`); return `${IMAGEKIT_URL_ENDPOINT}${transformations.length ? `tr:${transformations.join(',')}` : ''}/${_src}`; } } }); let overridenSrcSet = srcSets.map((src, index) => `${src} ${sizes[index]}w`).join(', '); // Skip override if image already load if (image.complete) { // If image is lazy load using data-src, override data-src to the master image if (!image.src) { overrideDatasrc && (image.dataset.src = overrideDatasrc); } return; } image.removeAttribute('src'); image.setAttribute('srcset', overridenSrcSet); image.setAttribute('src', srcSets.pop()); }); }); })(); </script> <!-- /sqs:image-loader-helper -->
FAQs
Question: How can I disable ImageKit.io?
To disable ImageKit.io integration on your Squarespace website, follow these simple steps:
Navigate to your Footer injection.
Remove the ImageKit.io script snippet.
This will neutralize the script and disable the integration.
Question: Can this script detect the correct image dimension and deliver it automatically?
No, this script only changes the base URL of your images to ImageKit.io endpoint URL. Image detection and size determination are handled by Squarespace and its ImageLoader. However, by caching and loading Squarespace images through ImageKit.io's CDN, your images are automatically optimized for format and quality.
Question: How do I make sure the integration is working?
After editing the suggested variables in the script and saving it to Footer injection:
Refresh your Squarespace website.
Check the image URLs; they should now start with
https://ik.imagekit.io/{endpoint-id}
.
To verify, use Chrome Developer Tools to ensure all images are loading via ImageKit.io and that they are displaying correctly. Note that the JavaScript custom code runs on the DOMContentLoaded event, but due to browser loading races, it may not override all image srcset
attributes on pages. Consequently, some images, especially above-the-fold, might still be served in their original format.
Conclusion
By exploring ImageKit.io for your Squarespace site, you gain an efficient solution for serving WebP images with automatic optimizations and detailed analytics. ImageKit’s on-the-fly transformations enhance performance and visual appeal, offering seamless format conversion without manual re-uploads.
If your primary focus is image delivery and detailed usage insights, ImageKit is the ideal choice. However, for more advanced features and video transformations, Cloudinary remains a strong alternative. Choose the option that best aligns with your specific needs for an optimized and engaging web experience.