Capture screen size at time of request

Asked

Viewed 47,574 times

8

I wonder if there is any way in Javascript 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 the occupied memory category, and it would be interesting to capture the screen size at the time of the request to serve the image with more appropriate weight to the user’s device.

  • 4

    I think when making the request to the server you have to send the device information, so the server will handle the information depending on the device.

  • Yes... Indeed. But how to access this data? Specifically speaking, the screen dimensions?

  • 1

    I think the @afsantos response is correct. I would go the same way :)

  • Screen size is not a parameter sent naturally in the HTTP request, you can create an extension for the browser that enters these values, or put a cookie with this data.

4 answers

14

This issue 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:

screen.height;
screen.width;

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:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

I tested them on the browser console (Firefox 27.0.1), and they all work. It is a matter of seeing which is the measure that interests you most, possibly that of the browser window.

I do not know if it is possible to send this data together with the page request. However, you can choose to Lazy charging of the images, if possible. I would use some temporary element in HTML to fill in the space, and make it clear to the user that something is still missing. Then load the right images as quickly as possible. Example:

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

Alternatively, you can take a look at the media queries of CSS3, help yourself. Here’s a article that talks a little about the subject.

  • Yes friend. Your suggestions are helpful.But the problem isn’t getting the sizes. It’s the time when these sizes are obtained. The most I can do is load these variables into the onload event. I’m looking for a way to load them the moment the browser requests the page. Because I think once the data is downloaded, there’s no point in me changing the images. I would have to do this during the request to decrease data traffic. You know?

  • 1

    @Pedrovinícius I understood, and added to the answer a few more suggestions.

3

Good morning buddy!

Well, we can divide your question into 2 steps: Screenshot and upload to server.

The friend @afsantos answered correctly how to catch the screen size:

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;

To be able to send this information to the server, it would be interesting to use ajax.
Following the same pattern as the Jquery-free alternative, the code would look like this:

var xmlhttp;

/* Requisição Ajax para o servidor */
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "http://servidor/pagina.php?width="+x+"&height="+y, true);
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
         document.getElementById("id_div").innerHTML = '<img src="' + xmlhttp.responseText + '" />'
    }
}
xmlhttp.send();

In this case, the xmlhttp.responseText would be the server response, containing the URL of the best image to be loaded, according to the width and height parameters you passed.

2

You can use the following to define the src of the image as soon as the tag img is rendered:

<img src="" onerror="this.src = 'http://myserver/myimage?w=' + screen.width + '&h=' + screen.height" />

Accordingly, the screen.width and the screen.height will be passed as image loading parameters to the server, which can then return the image of the most appropriate size.

Or you can do the processing you find most due within the event Handler error to load the most appropriate image.

The event error is called because the image tag has the empty src at first... if you try to load an image, and then error loading the onerror will be called again, and so will loop. Therefore, the ideal would be to clear the event so that it runs only once.

1

You ask about Javascript, then the way is to send the data via Ajax and make a redirect. Then when you reload the page, you will already have the data saved in Session there on the server (sent by Ajax request just before).

The sequence would be:

  1. The server has the screen size data in Session?

  2. If yes, send the page in the right measure.

  3. If not, send only minimal Javascript to:

    • get the data and then send it via Ajax (and the server writes the data to Session);

    • in the callback, location.reload() or window.location = '...' to (re)load;

    • ready - we are back at point 1 (and the answer will be "yes").

(If you don’t want Ajax, you can even put the screen size data in query string.)


But if you didn’t speak in Javascript, my answer would be pure CSS: use @import conditional with media queries!

The idea is to load a specific CSS file according to the screen size. You can easily place an image as background-image of a div or other element (no need to specify image URL on img of HTML).

Sort of like this:

@import url('grande.css') screen and (min-width: 1080px);
@import url('medio.css') screen and (min-width: 640px);
@import url('pequeno.css') screen and (min-width: 256px);

You don’t even need Javascript - the image will be chosen by the CSS that will be imported according to the screen size.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.