如何在Laravel PHP中获取客户端DOM宽度

I don't know if this is even possible, but I'd appreciate any help.

  • How do I get the client's DOM width in Laravel?
  • Basically, is there a way to extract the client's screen width from the $request?
  • Or are there any functions in Laravel or Blade that will give me a screen width value?

I know that I can get the DOM width with jQuery $(document).width(), but I need the width value on server side; before any js is executed.

@ArturGrigio You can try set JavaScript cookie and access it in Laravel. When user visits your website, get the screen size with JS (window.width) and store it in a cookie screen=WxH In Laravel $screen = Cookie::get('screen');

$screen = explode("x", $screen);
$width = $screen[0]
$height = $screen[0];

This is 1 solution to do it.

Unfortunately the is no way to get screen size info from PHP. You can try to play around with User Agent and detect if it is a mobile or desktop or tablet. and make fix sizes for those 3 types.

A good User Agent package for Laravel

I’ve been searching the internet for the past hour, and I didn’t find anything better than hacks and tricks. I didn't even find a good Node.js cross-OS, cross-Browser package to solve this problem...

But to anyone that has a similar question, here is my workaround (even though I still think there might be a better way to achieve the desired outcome, like @Froxz).

Possible Solution: I used an awesome lazy-load library by Ress.io called LazyLoadXT.

Here is a standard img html tag:

<img src="https://i.stack.imgur.com/5coxi.jpg" width="300px">

Here it is with LazyLoadXT:

<head>
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://ressio.github.io/lazy-load-xt/dist/jquery.lazyloadxt.js"></script>
</head>
<img data-src="https://i.stack.imgur.com/5coxi.jpg" width="300px" src="">

And here it is with LazyLoadXT + JavaScript:

<head>
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <script src="https://ressio.github.io/lazy-load-xt/dist/jquery.lazyloadxt.js"></script>
</head>
<script>document.write('<img data-src="https://i.stack.imgur.com/5coxi.jpg" width="' + document.documentElement.clientWidth + 'px" src="">')</script>

This is still ajax (which I was trying to avoid), but it is the cleanest solution I was able to think of.

DEMO: jsFiddle