用基于设备宽度的PHP变量替换图像源值

I'd like to be able to able to swap an img's src value with a variable created in PHP.

I currently am using javascript to determine the device width. This is happening within the .php file containing the Wordpress loop. Upon recognizing the device width, I would like to change the img's src value accordingly.

I can successfully retrieve the PHP variables using this JS function however only when the function is written in the loop, and as you all know, this will duplicate the function for each post and is resulting in an error.

I need to be able to calculate these given PHP variables outside the loop and then inject them into the img src value inside the loop.

I recognize I may have more errors in this code than what I am looking to resolve! I have been working on this for some time and this particular issue has become quite troubling. Thanks in advance.

Current Code in Use:

<?php query_posts( array ( 'home' => 'WordPress Themes', 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
  <script>
    function getImagePath(){
      if (window.matchMedia('(max-device-width: 1920px)').matches) {
        var theSizedImage = <?php the_field('desktop_image'); ?>
      }if (window.matchMedia('(max-device-width: 1280px)').matches) {
        var theSizedImage = <?php the_field('tablet_image'); ?>
      }if (window.matchMedia('(max-device-width: 600px)').matches) {
        var theSizedImage = <?php the_field('mobile_image'); ?>
      }
      return theSizedImage;
    } 
   </script>
   <img src="pixel.gif" onload="this.onload=null; this.src=getImagePath();"  />
<?php endwhile;
wp_reset_query();
?>

So after much further tinkering, I was able to come up with a solution. This does in fact work, however I wonder if there is a far more elegant solution. You will note my query has changed slightly as I improved the page and took care of errors. The main problem with the above code was that the variables for the image URLs were getting defined only once. The solution I have provided below will rerun for each of the posts in the loop.

<?php query_posts( array ( 'category__not_in' => array( 1, 4, 5, 6, 7 ), 'orderby' => 'rand', 'posts_per_page' => -1 ) ); ?>
<?php while ( have_posts() ) : the_post(); ?>
    <script>
       if (screen.width <= 1920) {document.write("<img src='<?php the_field('desktop_image');?>'   />");}
       if (screen.width <= 1280) {document.write("<img src='<?php the_field('tablet_image');?>'  />");}
       if (screen.width <= 600) {document.write("<img src='<?php the_field('mobile_image');?>'  />");}
       if (screen.width > 1920){document.write("<img src='<?php the_field('full_resolution');?>'  />");}
    </script>
<?php endwhile;
wp_reset_query();
?>