javascript - 图像在另一个任何部分完成页面加载后加载

标签 javascript html

首先,我的主要目标是在页面加载后加载图像。接下来,我不想在 HTML 代码中指定图像标记,因此不需要提供任何 src 属性。

假设这是我的标签,应该在页面加载后加载图像

<head>
    <p title="image_source" style="height:100px;width:100px;"></p>
</head>

var imagetag = document.createElement('img');
window.addEventListener('load', function() {
    for (var x=0; x < document.getElementsByTagName('p').length; x++) {

    }
});

最佳答案

就我个人而言,我会使用数据属性和类在页面加载后将图像添加到页面中。

window.addEventListener("load", function () {
  var imgs = document.querySelectorAll(".img_load")
  imgs.forEach(function (el) {
     var img = document.createElement("img");
     img.src = el.dataset.src
     el.appendChild(img);
  });
});
<p class="img_load" data-src="http://via.placeholder.com/350x150" style="height:100px;width:100px;"></p>
<p class="img_load" data-src="http://via.placeholder.com/450x150" style="height:100px;width:100px;"></p>
<p class="img_load" data-src="http://via.placeholder.com/350x450" style="height:100px;width:100px;"></p>

关于javascript - 图像在另一个任何部分完成页面加载后加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47872391/

相关文章:

html - 如果不推荐使用 contextmenu 如何替换它?

javascript - 如何通过jQuery检查后台url的value值

javascript - 添加自定义单元格图像/叠加水印

jquery - 如何更改 Bootstrap 中下拉菜单的动画?

javascript - location.href 使目标在悬停在链接上时出现在状态栏中

javascript - 使用 cookie 更改 header 内容

javascript - 数据表:未捕获类型错误:使用按钮插件时无法读取未定义的属性 'copy'

javascript - 使用 javascript 限制对全局上下文的访问

javascript - 无法使用页面标记 youtube api 搜索获取搜索的第二页

html - 禁用的文本区域无法在 Windows Phone 上滚动