用于检测外部javascripts何时加载的JavaScript [英] JavaScript to detect when external javascripts are loading

查看:54
本文介绍了用于检测外部javascripts何时加载的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法(事件监听器或其他方式)来检测特定外部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?

就我的目的而言,仅仅检查一个已知对象是否存在或类似的东西是不够的。相反,无论JS文件的内容如何,​​我都需要能够检测JS文件加载/加载的东西。

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.

推荐答案

以下示例适用于Chrome。它在head标签的onload事件上附加一个处理程序,然后添加一个外部javascript文件。加载文件后,将捕获事件并显示警告。

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

这篇关于用于检测外部javascripts何时加载的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆