How to find out which javascripts are loaded in javascript?

只愿长相守 提交于 2020-02-04 20:42:53

问题


Following up on a comment on another I question I asked myself if there's a way to get a list of all js code that is loaded on a page. Something like what firebug or chrome inspector do.

Is there a pure javascript way for that?

One way would be to scrape for script tags, but then you could miss dynamically loaded js. I'd hope for an API.

In the case of the other question, one could grep all the scripts for calls to console.debug() to prevent forgetting them and letting them slip into production.

Thanks


回答1:


I can't think of something that doesn't require a lot of work. Here's my initial failed attempt. It gets into infinite recursion as it tries to iterate through all the inner properties of window.

/**
 * You have to run this in firefox, pass window the first time
 * @return boolean Whether the given object contains a function where its
 * source code contains the word console.
 */ 
function lookForConsole( obj ) {
  var found  = false;
  for (var prop in obj) {
    var current = obj[prop];
    if (typeof current == "function") {

      if (current.toSource.indexOf("console" + ".log") != -1) {
        found = true;
        break;
      }
    } else if (typeof current == "object"){
      found = lookForConsole(current);
      if (found) {
        break;
      }
    }
  }
  return found;
}

You ever hear the expression, "when the only tool you have is a hammer, every problem looks like a nail"?

Why would you do this in JS?




回答2:


using jQuery:

$(document).ready(function() {


$('script').each(function() {
    if($(this).attr('src')) {
        alert($(this).attr('src'))
    }
    else {
        alert("inline")
    }
})

});




回答3:


This is how firebug does it. I guess there's no fancier way then.

    var doc = Firebug.browser.document;
    var scripts = doc.getElementsByTagName("script");
    var selectNode = this.selectNode = createElement("select");

    for(var i=0, script; script=scripts[i]; i++)
    {
        // Don't show Firebug Lite source code in the list of options
        if (Firebug.ignoreFirebugElements && script.getAttribute("firebugIgnore"))
            continue;

        var fileName = getFileName(script.src) || getFileName(doc.location.href);
        var option = createElement("option", {value:i});

        option.appendChild(Firebug.chrome.document.createTextNode(fileName));
        selectNode.appendChild(option);
    };

http://fbug.googlecode.com/svn/lite/branches/firebug1.3/content/firebug/script.js



来源:https://stackoverflow.com/questions/4091538/how-to-find-out-which-javascripts-are-loaded-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!