javascript - 使用 Javascript 将 src 属性写入 data-src,因为页面正在加载

标签 javascript html user-agent

Background: Back in December I wanted my (custom) PHP page-building engine to build a page one-way if the User Agent (UA) could handle Javascript and a different way if the UA could not. To achieve this, I needed to learn:

How to detect UA Javascript capability via PHP, prior to PHP building the page on-the-fly: Detecting javascript in PHP, before PHP builds page

Thanks to some very helpful guidance from @skobaljic, @Abhi Beckert and @GolezTrol, I learned that we can use Javascript to place a session cookie which PHP will be able to query on all subsequent page loads. Consequently, for every page after the first one, PHP will know whether the UA is Javascript-capable or not

So far, so good. Now I have reached the stage where I am no longer building pages with PHP on-the-fly but pre-generating them and uploading them to the server as static HTML documents.

If you're still with me, you'll have guessed correctly this means I am currently needing to pre-generate two static documents for each page - one for the non-JS-capable UAs and one for the JS-capable UAs. This isn't really ideal, hence my question below.

从表面上看,这看起来应该是一个简单的问题。

对于不支持 Javascript 的 UA,我想构建一个包含如下行的文档:

<img src="/myfolder/myimage.png" alt="My Image" />

对于支持 Javascript 的 UA,我想构建包含如下行的相同文档:

<img data-src="/myfolder/myimage.png" alt="My Image" />

(对于那些好奇的人,onload 之后的 javascript 将所有数据源属性转换为源属性,随后发生数十次服务器往返,但 - 关键 - 仅在 页面已经加载完毕)。

我已经通过 PHP 和 session cookie 实现了这一点(参见上面的背景),但现在,如果可能的话,我想在前端执行整个过程。

如何将属性写入 <img /> DOM 中的元素为 src默认情况下,但另外,(如果 javascript 可用)在该属性前加上 data- 前缀所以它读作 data-src ...

...这样...

[重要的一点]

如果 UA 支持 javascript,它将自动并立即写入 src 的所有实例作为data-src 因为 UA 正在下载页面,所以在 onload 之后然后 javascript 可以重写 data-src 的所有这些实例作为src再次。

最佳答案

像这样 - 未经测试但应该可以工作:

var imgs = document.getElementsByTagName('img');

for(var i = 0; i < imgs.length; i++) {
  var currentSrc = imgs[i].getAttribute('src');
  imgs[i].setAttribute('src',''); // remove old src data 
  imgs[i].setAttribute('data-src','currentSrc');
}

所有这一切都是添加一个新的 data-src属性,并清除当前的 src (如果需要)

</body> 之前添加标记

关于javascript - 使用 Javascript 将 src 属性写入 data-src,因为页面正在加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29578186/

相关文章:

c# - 如何使用 C# 评估 html 复选框?

Javascript 下拉列表

javascript - 在 Javascript/PHP 中处理绝对 URL 的正确方法?

javascript - 在绝对定位元素上同时淡入/淡出的 JQuery 错误

html - 有没有办法在不使用表格的情况下创建可水平滚动的容器?

javascript - 如何防止 SVG 绘图中的对象在 Chrome 中的 SVG 元素边界处被裁剪?

perl - 如何在 Mojo::UserAgent 中设置自定义用户代理字符串

java - Jsoup 读取超时取决于 UserAgent 字符串

ios - 更改用户代理

javascript - 处理 Angular 5 组件中的模型更改(双向绑定(bind))