JavaScript to detect when external javascripts are loading

前端 未结 5 959
一个人的身影
一个人的身影 2020-12-30 09:42

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, do

5条回答
  •  青春惊慌失措
    2020-12-30 10:46

    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); 
    }
    

提交回复
热议问题