我可以用什么来代替document.write

问题描述 投票:0回答:1
   if (a.indexOf('?q=') == -1 && a.indexOf('.html') == -1) {
        if (a.indexOf('/search/label/') == -1) {
            currentPage = 'page';
            if (locationrl.indexOf('#PageNo=') != -1) {
                currentPageNo = locationrl.substring(locationrl.indexOf('#PageNo=') + 8, locationrl.length)
            } else {
                currentPageNo = 1
            }
            document.write('<script src=\'' + home_page + 'feeds/posts/summary?max-results=1&alt=json-in-script&callback=dataFeed\'><\/script>')
        } else {
            currentPage = 'label';
            if (a.indexOf('&max-results=') == -1) {
                postResults = 20
            }
            if (locationrl.indexOf('#PageNo=') != -1) {
                currentPageNo = locationrl.substring(locationrl.indexOf('#PageNo=') + 8, locationrl.length)
            } else {
                currentPageNo = 1
            }
            document.write('<script src="' + home_page + 'feeds/posts/summary/-/' + postLabel + '?alt=json-in-script&callback=dataFeed&max-results=1" ><\/script>')
        }
    }

在这段代码中,我可以用什么来代替document.write?Google Pagespeed告诉我不要使用document.write。

javascript php jquery blogger pagespeed
1个回答
0
投票

如果你想使用JavaScript创建一个标签,那么你最好的选择和最常见的解决方案是使用 createElement 方法,该方法接收一个字符串,指定要创建的标签。

document.createElement()

这个方法接收一个字符串,用来指定你要创建的标签。比如说一个div。

document.createElement("div")

然后,为了实际插入这个元素 DOM 你需要把它附加到另一个标签上,比如说...。body

const body = document.getElementsByTagName("body")[0]
const div = document.createElement("div")

body.appendChild(div)

最后,要设置src或href等属性,你需要调用 setAttribute 方法,该方法接收2个字符串 - namevalue:

div.setAttribute("background", "red")

0
投票

通过DOM元素注入脚本标签的一个小窍门与 document.write 是用DOM方法动态创建插入的脚本是用 async true。这在你的情况下可能无所谓,但如果你想让脚本阻止以后的脚本执行,就像它在使用 document.write 不加掩饰 asyncdefer 属性,您必须确保将其设置为 asyncfalse 明确的DOM元素上。

if (a.indexOf('?q=') == -1 && a.indexOf('.html') == -1) {
  const script = document.createElement('script');
  script.async = false;

  currentPageNo = (locationrl.indexOf('#PageNo=') != -1)
    ? locationrl.substring(locationrl.indexOf('#PageNo=') + 8, locationrl.length)
    : 1;

  if (a.indexOf('/search/label/') == -1) {
    currentPage = 'page';
    script.src = `${home_page}feeds/posts/summary?max-results=1&alt=json-in-script&callback=dataFeed`;
  } else {
    currentPage = 'label';
    if (a.indexOf('&max-results=') == -1) {
      postResults = 20
    }
    script.src = `${home_page}feeds/posts/summary/-/${postLabel}?alt=json-in-script&callback=dataFeed&max-results=1`
  }
  document.head.appendChild(script); // or wherever you want to inject it
}

当然,有了 async更好所以,如果你不需要阻止后面的脚本执行,你可以留下 script.async = false 关闭。但看起来你正在设置全局的JavaScript变量,所以很可能你确实想要非异步行为。

© www.soinside.com 2019 - 2024. All rights reserved.