最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to load body background image after page loads(after load all site images) fully? - Stack Overflow

programmeradmin3浏览0评论

I want to load body background image for my website. It is very large size so it takes long time to load my page. So I want to load body background image after getting page fully loaded.

I tried javascript window.onload but it doesn't help.

I want to load body background image for my website. It is very large size so it takes long time to load my page. So I want to load body background image after getting page fully loaded.

I tried javascript window.onload but it doesn't help.

Share Improve this question asked Apr 20, 2013 at 16:22 LoganLogan 1,6944 gold badges21 silver badges35 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

If you are using jQuery, you could do this (http://api.jquery./ready/):

JS:

$(document).ready(function() {
    $('body').addClass('large-background');
});

CSS:

.large-background {
    background: url('../img/large-image.jpg') no-repeat;
}

Try something like this - remove the src attribute from the image first:

$(function() {
   $('img#bg').attr('src', 'images/myImage.jpg');
});

Put the body background at the end of the page in a style tag.

<style type='text/css'>body{background-image:url("/images/bgimage.gif")}</style>

I have made a script for my carousel with Jquery:

  1. Count all divs with class [classname]

  2. Get each div data-src

  3. Set for each div - style (background)

    $(document).ready(function(){
       var numBackground = $('.main-view-carosel').length /*amount of divs with 
       class*/
       console.log(numBackground);/*view the lenth*/
    
        setTimeout(function(){ /*set time out if needs to see ho it works*/
    
           for (let i = 0; i < numBackground; i++ ){ /*set the maximal [i] 
              amount of existing elements*/
              var elements = document.getElementsByClassName('main-view- 
              carosel');//get el with needed classname
              var requiredElement = elements[i]; /*get first one, second, third, 
              etc [i]*/
              var image = $(requiredElement).attr("data-src")/*get this div 
              data-src*/
              console.log(image);/*view in console this data-src*/
              requiredElement.style.backgroundImage = "url(" + image + ")";/*set 
              background for current div*/
           }
        }, 100);
    });
    

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论