2017-09-15 114 views
1

我試圖通過在index.html的頭部添加一個腳本來獲取網頁中所有未加載的元素,但我遇到了一些問題。
這是代碼:如何獲取未加載的資源?

document.addEventListener('DOMContentLoaded', function() { 
     console.log("here"); 

     var scripts = document.getElementsByTagName('script'); 
     for(var i=0;i<scripts.length;i++){ 
      scripts[i].onerror =function(message, source, lineno) { 
       console.log("JS: Error SCRIPT"); 
      } 
     } 


     var imgs = document.getElementsByTagName('img'); 
     for(var i=0;i<imgs.length;i++){ 

      imgs[i].onerror =function(message, source, lineno) { 
       console.log("JS: Error IMG "); 
      } 
     } 

     var links = document.getElementsByTagName('link'); 
     for(var i=0;i<links.length;i++){ 
      links[i].onerror = function(message, source, lineno){ 
       console.log("JS: Error CSS "); 
      } 
     } 

    }); 

我把3錯CSS,圖片和腳本(它們不存在的資源)的HTML文件,其中我調用腳本里面。
當我在本地運行index.html時,我得到「錯誤IMG」和「錯誤CSS」。
當我在服務器上運行時,我只得到「錯誤IMG」。
在這兩種情況下,我都沒有得到「Error SCRIPT」。
我在做什麼錯了?

UPDATE:這是代碼

appmetrics.js

//class that store page resource data 
    /* 
    ES6 
    class Resource{ 
     constructor(name,type,start,end,duration){ 
      this.name = name; 
      this.type = type; 
      this.start = start; 
      this.end = end; 
      this.duration = duration; 
     } 
    } 
    */ 
    function Resource (name,type,start,end,duration){ 
     this.name = name; 
     this.type = type; 
     this.start = start; 
     this.end = end; 
     this.duration = duration; 
    } 

    /* 
    ES6 
    class Errors{ 
     constructor(name,source,line){ 
      this.name = name; 
      this.source = source; 
      this.line = line; 
     } 
    } 
    */ 
    function Errors(name,source,line){ 
     this.name = name; 
     this.source = source; 
     this.line = line; 
    } 

    //endpoint to send data 
    var endpoint = "https://requestb.in/sr8wnnsr" 

    var resources = Array(); 
    var errors = Array(); 
    var pageLoadTime; 

    var start = performance.now(); 

    window.onload = function(){ 

     pageLoadTime = performance.now()-start; 

     console.log("Page loading time: " + pageLoadTime); 

     //getting page resources and pushing them into the array 
     var res = performance.getEntriesByType("resource"); 
     res.forEach(function add(item){ 
      resources.push(new Resource(item.name,item.initiatorType,item.startTime,item.responseEnd,item.duration)); 
     }) 

     console.log(resources); 
     var jsonRes = JSON.stringify(resources); 
     //sendMetricToEndpoint(jsonRes); 
     //sendMetricToEndpoint(pageLoadTime.toString()); 

    } 

    window.onerror = function(message, source, lineno) { 
     console.log("Error detected!" + "\nMessage: " +message +"\nSource: "+ source +"\nLine: "+ lineno);  
     errors.push(new Errors(message,source,lineno)); 
     console.log(errors); 
    } 

    //Not working code 
    /* 
      document.addEventListener('DOMContentLoaded', function() { 
       console.log("here"); 

       var scripts = document.getElementsByTagName('script'); 
       for(var i=0;i<scripts.length;i++){ 
        scripts[i].onerror =function(message, source, lineno) { 
         console.log("JS: Errore SCRIPT"); 
        } 
       } 


       var imgs = document.getElementsByTagName('img'); 
       for(var i=0;i<imgs.length;i++){ 

        imgs[i].onerror =function(message, source, lineno) { 
         console.log("JS: Errore IMG "); 
        } 
       } 

       var links = document.getElementsByTagName('link'); 
       for(var i=0;i<links.length;i++){ 
        links[i].onerror = function(message, source, lineno){ 
         console.log("JS: Errore CSS "); 
        } 
       } 

      }); 

    */ 

    //StackOverflow solution start 

    var scripts = []; 

    for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) { 
    scripts[i] = { source: nodes[i].src, loaded: false }; 
    nodes[i].onload = function() { 
     var loadedNode = this; 
     var index = scripts.findIndex(function(script) { 
     return script.source === loadedNode.src; 
     }); 

     scripts[index].loaded = true; 

    }; 
    } 

    var links = []; 

    for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) { 

    links[i] = { source: nodes[i].href, loaded: false }; 

    nodes[i].onload = function() { 
     var loadedNode = this; 
     var index = links.findIndex(function(link) { 
     link.href === loadedNode.href; 
     }); 

     links[index].loaded = true; 

    }; 
    } 

    document.addEventListener('DOMContentLoaded', function() { 
    console.log("here"); 
    scripts.filter(function(script) { 
     return !script.loaded; 
    }).forEach(function(script) { 
     console.log("Error loading script: " + script.source); 
    }); 

    links.filter(function(link) { 
     return !link.loaded; 
    }).forEach(function(link) { 
     console.log("Error loading link: " + link.source); 
    }); 

    // and the rest of the elements 

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

    for (var i = 0; i < imgs.length; i++) { 

     imgs[i].onerror = function() { 
     console.log("Error loading image: " + this.src); 
     }; 

    } 
    }); 

    //StackOverflow solution stop 

    /** 
    * Function that send metric to endpoint. 
    * 
    * @param {string} endpoint Where to send data. 
    * @param {*} data data to send (JSON or string) 
    */ 
    function sendMetricToEndpoint(data){ 
     console.log("Sending metrics to endpoint"); 

     var xhttp; 
     xhttp=new XMLHttpRequest(); 

     xhttp.onreadystatechange = function() { 
     if (xhttp.readyState == 4 && xhttp.status == 200) { 
      console.log(xhttp.responseText); 
     } 
     }; 
     xhttp.open("POST", endpoint, true); 
     //xhttp.setRequestHeader("Content-type", "application/json"); 
     xhttp.send(data); 
    } 

的index.html

<html> 
    <head> 
      <!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>--> 
      <script src="js/appmetricsmod.js"></script> 
      <link rel="stylesheet" href="styletests.css"> 
      <link rel="stylesheet" href="styletestss.css"> 
      <link rel="stylesheet" href="styletestsss.css"> 
      <script src="js/error1.js"></script> 
      <script src="js/error2.js"></script> 
      <script src="js/error3.js"></script> 

    </head> 
    <body> 

    <img src="imgtest.png"></img> 
    <img src="imgErr1.png"></img> 
    <img src="imgErr2.png"></img> 
    <img src="imgErr3.png"></img> 
    <img src="http://images.centrometeoitaliano.it/wp-content/uploads/2016/11/15/l1.jpg"></img> 
    <div class="divtest"> 
     hello this is a test 
    </div> 


    <script> 

    </script> 
    </body> 
    </html> 
+0

爲什麼不記錄實際的錯誤消息? –

+0

你的意思是使用「window.onerror」? –

+0

語句'console.log(「JS:Error IMG」);'是沒用的,因爲它根本沒有告訴你任何有用的東西。首先將其更改爲'console.error',其次將*實際錯誤消息*('message')添加到日誌中。 – Amy

回答

1

使用上述類資源和錯誤,我採取了網頁的所有資源,然後除去做事的人,解決了這個問題。結果是一個未加載資源的數組。
這是代碼:

 var res = performance.getEntriesByType("resource"); 
     res.forEach(function add(item){ 
      resources.push(new Resource(item.name, 
      item.initiatorType, 
      item.startTime, 
      item.responseEnd, 
      item.duration)); 
     }) 

var flag = true; 
var imgs = document.getElementsByTagName('img'); 
for(var i=0;i<imgs.length;i++){ 
    for(var j=0;j<resources.length;j++){ 
     if(imgs[i].src == resources[j].name){ 
      flag = false; 
     } 
    } 
    if(flag && imgs[i].src){ 
     errors.push(new Errors("RES NOT FOUND",imgs[i].src,null)); 
    } 
    flag = true; 
} 

var scripts = document.getElementsByTagName('script'); 
for(var i=0;i<scripts.length;i++){ 
    for(var j=0;j<resources.length;j++){ 
     if(scripts[i].src == resources[j].name){ 
      flag = false; 
     } 
    } 
    if(flag && scripts[i].src){ 
     errors.push(new Errors("RES NOT FOUND",scripts[i].src,null)); 
    } 
    flag = true; 
} 

var links = document.getElementsByTagName('link'); 
for(var i=0;i<links.length;i++){ 
    for(var j=0;j<resources.length;j++){ 
     if(links[i].src == resources[j].name){ 
      flag = false; 
     } 
    } 
    if(flag && links[i].href){ 
     errors.push(new Errors("RES NOT FOUND",links[i].href,null)); 
    } 
    flag = true; 
} 

console.log(resources); 
console.log(errors); 
2

可悲的是與onerror事件,你也同樣不能得到link也不script錯誤負載,但您可以處理加載的內容,並過濾未加載的內容。對於linkscript標籤,可以使用load事件。

var scripts = []; 

for (var i = 0, nodes = document.getElementsByTagName('script'); i < nodes.length; i++) { 

    scripts[i] = { source: nodes[i].src, loaded: false }; 

    nodes[i].onload = function() { 
    var loadedNode = this; 
    var index = scripts.findIndex(function(script) { 
     return script.source === loadedNode.src; 
    }); 

    scripts[index].loaded = true; 

    }; 
} 

var links = []; 

for (var i = 0, nodes = document.getElementsByTagName('link'); i < nodes.length; i++) { 

    links[i] = { source: nodes[i].href, loaded: false }; 

    nodes[i].onload = function() { 
    var loadedNode = this; 
    var index = links.findIndex(function(link) { 
     link.href === loadedNode.href; 
    }); 

    links[index].loaded = true; 

    }; 
} 

document.addEventListener('DOMContentLoaded', function() { 
    console.log("here"); 

    scripts.filter(function(script) { 
    return !script.loaded; 
    }).forEach(function(script) { 
    console.log("Error loading script: " + script.source); 
    }); 

    links.filter(function(link) { 
    return !link.loaded; 
    }).forEach(function(link) { 
    console.log("Error loading link: " + link.source); 
    }); 

    // and the rest of the elements 

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

    for (var i = 0; i < imgs.length; i++) { 

    imgs[i].onerror = function() { 
     console.log("Error loading image: " + this.src); 
    }; 

    } 
}); 

希望它能幫助:)

+0

的解決方案看起來不錯,但仍然沒有工作:( 現在我貼的問題 –

+0

我看到的代碼,什麼是你從JS得到的輸出的頂部? –