javascript – Capture screen size at request time


I would like to know if there is in JavaScript any way to execute methods at the time of the request that the client makes to the server. I have a project where I use several large images in terms of occupied memory, and it would be interesting to capture the screen size at the time of the request to serve the image with the most appropriate weight for the user's device.


This question on SOen may be of interest. In particular, I compile here some of the suggestions given.

Get page and browser sizes, with jQuery:

$(window).height();   // altura do browser
$(document).height(); // altura do documento HTML
$(window).width();   // comprimento do browser
$(document).width(); // comprimento do documento HTML

Get screen size:


Alternative without jQuery:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

Another way to get screen dimensions, apparently supported by browsers in general:


I tested them in the browser console (Firefox 27.0.1), and they all work. It's a matter of seeing which size interests you the most, possibly the browser window.

I don't know if it's possible to send this data along with the page request. However, you can choose to lazy load the images if possible. I would use some temporary element in the HTML to fill in the space, and let the user know that something is still missing. And then, order the right images to be uploaded as quickly as possible. Example:

<!DOCTYPE html>
        $(document).ready(function () {
           if ((window.screen.availHeight < 1234) &&
                   (window.screen.availWidth < 1234))
               document.getElementById("img1").src = "small";
               document.getElementById("img1").src = "big";
    <img id="img1" src=""/>
    <p>Algum texto.</p>

Alternatively, you can take a look at the CSS3 media queries if it helps. Here's an article that talks a little bit about it.

Scroll to Top