0

I can embed images on my page with specified width and height (like this: <img src="image.php?w=100&h=100">)

I want to load different image sizes depending on device screen width: 100x100 for screen widths lower than 600px and 200x200 in other cases. As I understand php knows nothing about user screen so I have to use JS.

This didn't work:

<img src="image.php?<script>document.write('w=100&h=100')</script>">

That worked:

<script>document.write('<img src="image.php?w=100&h=100">')</script>

Is that a correct way for doing this? Any consequences I should take into consideration?

Alex Velickiy
  • 510
  • 1
  • 4
  • 18
  • 1
    Do you have to do this server side? You could always use dynamic CSS (via Javascript) on the client side. The upshot is the you wouldn't have to generate and store a bunch of images server side. – grill May 28 '15 at 20:01
  • 1
    There's a new HTML5 element called `picture` that you might be interested in, but it's still a long way away from full browser support. Until then, a JavaScript solution is probably your best bet. [Article](http://www.html5rocks.com/en/tutorials/responsive/picture-element/) and [current browser support](http://caniuse.com/#feat=picture) – Pikamander2 May 28 '15 at 20:09
  • It is possible in server side because you can put custom param here. https://gradindesign.files.wordpress.com/2019/01/1_wlz32vkptgjya9xlzj0w6g.jpeg?w=499, if you download the image, it will has the same width/height you specified. You can also try to inspect element and see that smaller image will has smaller load size too. I'm still looking how wordpress do this. – Christhofer Natalius Jan 31 '19 at 05:04

1 Answers1

0

You can use that code. But I think that bst way is to change src of images on the server side.

function addParams(w, h) {
    var img = document.querySelectorAll("img.withParams");
    for (var i = 0; i < img.length; i++) {
        img[i].src = img[i].src + "?w=" + w + "&h=" + h;
    }
}

window.addEventListener("load", function () {
    addParams(10, 10);
})
<img class="withParams" src="img.php"/>    
<img src="img.php" />    
<img class="withParams" src="img.php" />
Microshine
  • 651
  • 3
  • 18