php/Ajax - Best practice for pre-loading images

时光毁灭记忆、已成空白 提交于 2019-11-30 10:21:12

To preload an image from Javascript, you don't need to do anything that sounds like AJAX or JSON. All you need is this:

var img = new Image();
img.src = "http://example.com/new/image.jpg";

The browser will quite happily load the image in the background, even though it's not displayed anywhere. Then, when you update the src field of another (displayed) image tag, the browser will immediately show the part of the image it's already loaded (hopefully all of it).

Fetching JSON Via Ajax will just slow you down.

You're better off using inline JSON and generated Javascript.

 <?php 
       $images = array( "foo.jpg","bar.jpg" ); 
 ?>
 <script type="text/javascript">
   jQuery(function($){
       var images = ( <?php echo json_encode($images); ?> ); 
       /* Creating A Hidden box to preload the images into */
       var imgbox = document.createElement("div"); 
       $(imgbox).css({display: 'none'});
       /* Possible Alternative trick */
       /* $(imgbox).css({height:1px; width: 1px; overflow: hidden;}); */
       $('body').append(imgbox);

       $.each( images , function( ind, item ) 
       {
          #Injecting images into the bottom hidden div. 
          var img = document.createElement("img"); 
          $(img).src("/some/prefix/" + item ); 
          $(imgbox).append(img);
       });
    }); 
 </script>

In the case where you want to concurrently preload a larger number of resources, a little ajax can solve the problem for you. Just make sure the caching headers are such that the browser will use the resources on the next request. In the following example, I load up to four resources concurrently.

<script>
var urls = [
  "a.png",
  "b.png",
  "c.png",
  "d.png",
  "e.png",
  "f.png"
];

var currentStep = 0;
function loadResources()
{
  if(currentStep<urls.length){
  var url = urls[currentStep];
  var req = GetXmlHttpObject();
  update('loading ' + url);
  req.open("GET", url, true);
  req.onreadystatechange = getUpdateState(req, url);
  req.send(null);
} else {
  window.location = 'done.htm';
}
}

function getUpdateState(req, url) {
  return function() {
    var state = req.readyState;
    if (state != 4) { return; }
    req = null;
    setTimeout('loadResources()', 0);
  }
}
</script>

<!-- This will queue up to four concurrent requests.  Modern browsers will request up to eight images at time  -->
<body onload="javascript: loadResources(); loadResources(); loadResources(); loadResources();">

Why not use text and replace the text with a picture code (works in php really nice with ajax up to 500 pictures and more)?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!