简体   繁体   中英

load HTML file with javascript

I need to load the content of an HTML file into a div.

I am doing it with the following javascript code

function scroll_down() {
  var div = $('#div_name');
  $.get('html_file_to_load.html', function(data) { 
      div.html(data);
      $('body, html').scrollTop(div[0].scrollHeight);
  })
}

the function loads the html_file_to_load.html file, add the content to a div, and then scrolls down the page. The problem is that the HTML file may contain some pictures

example < img src='picture.jpg' >

In this case what happens is that after the HTML code is loaded, the scroll bar is set to the bottom, the browser loads the pictures and the vertical height of the page increases !!

I need to add a check: the browser has to wait until the HTML file and pictures files eventually included in it are all loaded before executing scrollTop(div[0].scrollHeight);

How can I do this?

You can add event listeners to the images and force it to scroll when they load

function forceScroll(elem) {
  $('body, html').scrollTop(elem.scrollHeight);
}

function scroll_down() {
  var div = $('#div_name');
  $.get('html_file_to_load.html', function(data) {
      var html = $(data);
      var imgs = html.find("img");
      imgs.each(function() {
        $(this).on("load", function() {
          forceScroll(div[0]);
        });
      });
      div.append(html);
      forceScroll(div[0]);
    }
  });
}

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