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/