Responsive images using the cloudinary-core JS library

Last updated: Jan-24-2023

Using the cloudinary-core JS library, you can create the correct DPR (Device Pixel Ratio) image for devices that support higher resolutions, in addition to automating the width. The JavaScript code checks the DPR of the device as well as the space available for the image. Users of devices with high pixel density will get a great visual result, while low-DPR users don't have to wait needlessly for larger images to load.

If you want to automate only the width of the image without taking the device's DPR into account, then it is preferable to use the frontend frameworks solution.

Cloudinary's cloudinary-core library includes a method that automatically builds the dynamic image URLs and works as follows:

  • A Cloudinary dynamic transformation URL is automatically built on the fly to deliver an image that is scaled to the exact available width and resolution.
  • If the browser window is consequently enlarged then new higher resolution images are automatically delivered, while using breakpoint steps (every 100px by default) to prevent loading too many images.
  • If the browser window is scaled down, browser-side scaling is used instead of delivering a new image.

This feature allows you to upload one high resolution image to Cloudinary, and have it automatically adapt to the resolution and size appropriate to each user's device or browser on the fly.

Note
The JavaScript solution documented here dynamically replaces dpr_auto and w_auto with the actual values on the client side based on the actual browser settings and window width. In contrast, the Client-Hints based solution allows you to simplify your code and perform the dynamic decisions on the server side (CDN level) based on Client-Hints, but only for supported browsers.

Automating responsiveness with the cloudinary-core JS library

See how the layout and images (including the text overlays) dynamically respond to the width of the browser when this responsive solution is used. Follow the steps below to implement the responsive solution with the cloudinary-core JS library.

Notes

  • The text overlays change based on the DPR of the device and the width of the delivered image (l_text:Arial_18_bold:dpr_auto%0Aw_auto). dpr_auto and w_auto are replaced with the actual values on the client side based on the browser settings and window width.
  • When the browser width is wide, the first images delivered are smaller in dimensions. As you make the browser narrower, the individual columns get more space on the next breakpoint, so larger images are requested to fill the larger available space.
  • The change in overlay width indicates that a new image was requested and displayed.
  • When increasing the width of the page, as the largest version with the best resolution was already requested and delivered, that version is used and scaled down on the client side, so the overlays don't change back.

Try it yourself!

Step 1: include the Cloudinary JavaScript library

Include the Cloudinary cloudinary-core library in your HTML pages:

Copy to clipboard
<script
    src="{{install path/}}cloudinary-core-shrinkwrap.js"
    type="text/javascript">
</script>

Notes

  • The cloudinary-core-shrinkwrap.js library is a shrinkwrapped version of the cloudinary-core library (it is not dependent on lodash). See the GitHub JavaScript installation documentation for more information and details on the various library installation options (all the options include the responsive support as discussed here).
  • Instead of installing the files, the latest version of the cloudinary-core files can also be directly referenced from https://unpkg.com/cloudinary-core@latest/cloudinary-core-shrinkwrap.js. For production use, we recommend that you use a specific version, and not the latest, to protect yourself from any breaking changes.

Step 2: set the img tag parameters

For each image to display responsively:

  1. Set the data-src attribute of the img tag to the URL of an image that was uploaded to Cloudinary. There is no need to set the src attribute of the img tag as it is updated dynamically. However, you can optionally set the src attribute to a placeholder image that is displayed until the image is loaded.
  2. Set the crop parameter to limit and the width and dpr parameters to auto (c_limit,w_auto/dpr_auto in URLs). This allows the SDK to dynamically generate an image URL scaled to the correct width value, based on the DPR of the device and the detected width actually available for the image in the containing element.
  3. Add the cld-responsive class to the image tag. This is the default class name, but you can use custom class names and programmatically make HTML elements become responsive.

For example:

Copy to clipboard
<img 
    data-src="https://res.cloudinary.com/demo/image/upload/c_limit,w_auto/dpr_auto/smiling_man.jpg" 
    class="cld-responsive">

Step 3: call the Cloudinary responsive method

Add a call to Cloudinary's responsive JavaScript method at the end of the HTML page.

Copy to clipboard
<script type="text/javascript">
    var cl = cloudinary.Cloudinary.new({cloud_name: "demo"}); 
    // replace 'demo' with your cloud name in the line above 
    cl.responsive();
</script>

The responsive method looks for all images in the page that have the "cld-responsive" class name, detects the available width for the image on the page, and then updates the HTML image tags accordingly. The image is also updated whenever the window size or screen resolution changes.

Note
The process presented above covers the simplest and most general solution. The behavior can be further customized to control whether to update images on resize, when to update the image using stop-points, preserving the CSS image height, and more. For details, see the Cloudinary JavaScript library.

Responsive images using the cloudinary-core JS library interactive demo

Try this responsive demo to see how the browser loads different sized images based on the viewport width.

See notes on this demo.

View the demo code in GitHub.

Overriding default values

By default, the responsive method uses a breakpoint steps value of 100 pixels, and always uses the breakpoints to determine the width. These values can be overridden by using the config method to pass new values for the breakpoints and responsive_use_breakpoints parameters as follows:

breakpoints: A function or set of values to be used when resizing the browser window and a larger image needs to be delivered. For example:

  • a function to set the breakpoints steps to every 50 pixels:

    Copy to clipboard
    defaultBreakpoints = function(width) {  // width - the current width of the containing element
      return 50 * Math.ceil(width / 50);
    };
  • an array of values:

    Copy to clipboard
    defaultBreakpoints = [50, 90, 130, 170, 200, 300, 450, 550, 700, 850, 1000];

responsive_use_breakpoints: A string value determining when to use the breakpoint steps:

  • true - (default) always use breakpoints for width.
  • resize - use the exact width of the containing element on initial render, then proceed with breakpoints.
  • false - always use the containing element's width.

Both of the above parameters need to be passed with the config method. For example, calling to Cloudinary's responsive JavaScript method at the end of the HTML page, and also configuring the breakpoints step to every 50 pixels and to use the exact width of the containing element on initial render:

Copy to clipboard
<script type="text/javascript">
    my_breakpoints = function (width){  // width - the current width of the containing element
      return 50 * Math.ceil(width / 50);
    }
    var cl = cloudinary.Cloudinary.new({cloud_name: "demo"}); 
    // replace 'demo' with your cloud name in the line above 
    cl.config({breakpoints:my_breakpoints, responsive_use_breakpoints:"resize"})
    cl.responsive();
</script>

SDK support

The responsive design can be implemented with the Cloudinary SDK's helper methods (e.g. cl_image_tag in Ruby on Rails). Setting the crop parameter to limit and the width and dpr parameters to auto creates an HTML image tag with a blank src attribute while the data-src attribute points to a dynamic image transformation URL. When you load Cloudinary's cloudinary-core library and call the responsive method, the JavaScript code will check the DPR of the device as well as the space available for the image. The image tags are automatically updated and the image URLs are replaced with new URLs that include the updated width and DPR values. You can also set a placeholder image using the responsive_placeholder parameter, or set it to an inline blank image by setting the parameter to blank.

For example, creating an HTML image tag for the "smiling_man.jpg" image with the width automatically determined on the fly as needed, and using a blank image placeholder:

Ruby (cloudinary 1.x):
Copy to clipboard
cl_image_tag("smiling_man.jpg", :width => :auto, :crop => :limit, :dpr => :auto, :responsive => :true,
  :responsive_placeholder => "blank")
PHP (cloudinary_php 2.x):
Copy to clipboard
ImageTag::fromParams("smiling_man.jpg",  ["width" => "auto", "crop" => "limit", 
  "dpr" => "auto", "responsive" => "true",  "responsive_placeholder" => "blank"]);
PHP (cloudinary_php 1.x (legacy)):
Copy to clipboard
cl_image_tag("smiling_man.jpg",  ["width" => "auto", "crop" => "limit", 
  "dpr" => "auto", "responsive" => "true",  "responsive_placeholder" => "blank"]);
Python (cloudinary 1.x):
Copy to clipboard
cloudinary.CloudinaryImage("smiling_man.jpg").image(width = "auto", responsive = True,
  dpr = "auto", crop = "limit", responsive_placeholder = "blank")
Node.js (cloudinary 1.x):
Copy to clipboard
cloudinary.image("smiling_man.jpg",  { width: "auto", responsive: "true",
   dpr: "auto", crop: "limit", responsive_placeholder: "blank" })
Java (cloudinary 1.x):
Copy to clipboard
cloudinary.url().transformation(new Transformation().width("auto").responsive("true").
  dpr("auto").crop("limit").responsive_placeholder("blank")).imageTag("smiling_man.jpg");

The code above generates the following HTML image tag:

Copy to clipboard
<img 
    class="cld-responsive" 
    data-src="https://res.cloudinary.com/demo/image/upload/c_limit,w_auto/dpr_auto/smiling_man.jpg"
    src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"  />

✔️ Feedback sent!

Rate this page: