Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to detect when external javascripts are loading

Tags:

javascript

Is there a way (event listener or otherwise) to detect when a particular external javascript is about to load / is loading / has finished loading?

In otherwords, does the browser fire an event when it's about to load, is loading, and/or has finished loading a particular external script?

For my purposes it's not enough to simply check to see if a known object exists or anything like that. Instead, I need something that will detect a JS file is loading/loaded regardless of the contents of the JS file.

like image 720
Dan Avatar asked Jan 03 '12 20:01

Dan


2 Answers

The following example works in Chrome. It attaches an handler on the onload event of the head tag and then adds an external javascript file. When the file is loaded, the event is captured and an alert appears.

http://jsfiddle.net/francisfortier/uv9Fh/

window.onload = function() {
    var head = document.getElementsByTagName("head")[0];
    var script = document.createElement("script"); 

    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", "http://code.jquery.com/jquery-1.7.1.min.js");

    head.addEventListener("load", function(event) {
        if (event.target.nodeName === "SCRIPT")
        {
            alert("Script loaded: " + event.target.getAttribute("src"));
        }
    }, true);

    head.appendChild(script); 
}
like image 72
Francis Avatar answered Oct 19 '22 23:10

Francis


<script onload> will fire when a script is finished loading.

You will not be able to do something like:

<script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will not do what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.

like image 30
tkone Avatar answered Oct 19 '22 23:10

tkone