简体   繁体   中英

how to load images in a javascript variable locally

I had help with this background carousel made with jquery for a website and it works just great.. except that i find that the page can take a while to load initially.. i thought that if i actually downloaded the pictures that i'm using for the background instead of loading them via ' http://www.whatever.jpg ', that the page might load faster.. but i'm kind of a noob still.. and haven't been able to figure out why this isn't working.. Here is my code:

var images = [
//even though I downloaded the picture and its in the same folder as this file.js, the background just loads a black page, then the other 2 load fine.
"bg1-orig.jpg",
"http://www.desktopaper.com/wp-content/uploads/Cool-Hd-Wallpapers-2.jpg",
"http://wallpaperscraft.com/image/restaurant_table_interior_modern_style_39288_1920x1080.jpg"
];

var $body = $("body"),
$bg = $("#bg"),
n = images.length,
c = 0; // Loop Counter
num = 200;

// Preload Array of images...
for(var i=0; i<n; i++){
var tImg = new Image();
tImg.src = images[i];
}

$body.css({backgroundImage : "url("+images[c]+")"});

(function loopBg(){
  $bg.hide().css({backgroundImage : "url("+images[++c%n]+")"}).delay(7000).fadeTo(2200, 1,      function(){
$body.css({backgroundImage : "url("+images[c%n]+")"}); 
loopBg();
});
}());

i've searched around for a while now... thanks for the help!

You do yourself no favors trying to pre-load the images right before they are loaded for display in your CSS. In either case, the images have to be loaded first before you can see them, so there is going to be a delay regardless.

If the only thing that you want to change is the src attribute of the img s to be a local folder, then I assume the only change to otherwise working code is the strings in your images array point to local files.

If that's the case, and if you want to resolve the location correctly without adding some sort of directory changes ( ../ , img/ or the like), then you will need those images to be in the same directory as the html file , not the file.js file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM