Use jQuery to find all images on a (different) page via ajax for preloading
-
21-07-2021 - |
Question
I'm building a app - converted from flash to html/js and using jQuery. Pages/scenes are pulled in via ajax and I have a 'loading' overlay in place until these are loaded however in addition I want to preload images for the next and previous pages.
So I pull in page-5.php via ajax then I need to preload the images in the background for pages 4/6 to speed things up for the user.
I have a preload function I can insert an array of images into - the tricky bit is using ajax to find the src of all images on page-6.php for example.
So I need a call to: - find all images on page-6.php, grab their src's into an array. possible?
I guess I could hide an array on each page containing the images and grab this but I'd rather keep it all dynamic.
Any thoughts / help much appreciated.
Solution
you should be able to parse the html response with regular jquery:
$.ajax({
url:[your url],
success: function(data) {
$("img", data).each(function() {
alert($(this).attr("src");
});
}
});
EDIT:
$.ajax({
url: 'http://localhost:8888/site/scenarios/scenario-1.php',
success: function(data) {
$("img", data).each(function() {
alert( $(this).attr("src") );
});
}
});
OTHER TIPS
I would suggest to preload the next/prev page in a two hidden div on the same page, which is not shown until selected. That way you don't have to do any parsing/loading from your side, as the browser will handle it nicely.
Here is an example on how to use ajax to load a tab, but in your case you would need to prefetch the left and right div, instead of loading it when clicked.