简体   繁体   English

如何使我的JavaScript更快且异步运行

[英]How can I make my javascript run faster and asynchronously

I'm trying to make an extension that adds some HTML to a page as it's loaded. 我正在尝试进行扩展,以便在加载页面时向页面添加一些HTML。 Long story short, it gets a list of links in a table, loads those links, and grabs a specific string and adds it to the original page I loaded. 长话短说,它获取表中的链接列表,加载这些链接,并获取特定的字符串并将其添加到我加载的原始页面中。

Here is the code: due to the way the webpage was coded, i couldn't get the unique ids because they didn't exist so ignore that part. 这是代码:由于网页的编码方式,我无法获得唯一的ID,因为它们不存在,因此请忽略该部分。

var xhr = new XMLHttpRequest();
  for (i = 0; i < length; i++) {
    url = rows[i].getElementsByTagName("td")[0].getElementsByTagName('a')[0].getAttribute('href');
    insert = rows[i].insertCell(-1);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            //var Data = JSON.parse(xhr.responseText);
            var htmlString = xhr.responseText
              , parser = new DOMParser()
              , doc = parser.parseFromString(htmlString,"text/html")
              , test = doc.getElementById('page-wrapper').children[1]
              , ip_address = doc.getElementsByClassName('col-md-5')[0].children[5].children[0].children[0].children[10].innerHTML;
            insert.innerHTML = ip_address;
          }

    };
      xhr.open("GET",url,false);
      xhr.send();
    }

when i call the function, it works fine, however it takes a really long time to load and it all loads at the end rather than updating as each iteration of the for loop completes. 当我调用该函数时,它可以正常工作,但是要花很长时间才能加载,并且全部加载到最后,而不是在for循环的每次迭代完成时进行更新。 I'd like to decrease the time it takes to load but a significant amount, and possibly have ear row update instantly vs at the end. 我想减少加载所需的时间,但要减少很多,并且可能要比在最后立即更新耳排。 I've tried searching asycn javascript but the bit of code I tried didn't help me much. 我已经尝试搜索asycn javascript,但是我尝试的一些代码并没有太大帮助。 Any assistance would be appreciated. 任何援助将不胜感激。

Using modern Javascript: 使用现代Javascript:

 rows.forEach(row => { fetch(row.querySelector('td:first-of-type a:first-of-type').getAttribute('href')) .then(res => res.json()) .then(data => { // do manipulations with DOM }) .catch(console.log) }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM