• [f]动态判断js加载完成


    在正常的加载过程中,js文件的加载是同步的,也就是说在js加载的过程中,浏览器会阻塞接下来的内容的解析。这时候,动态加载便显得尤为重要了,由于它是异步加载,因此,它可以在后台自动下载,并不会妨碍其它内容的正常解析,由此,便可以提高页面首次加载的速度。

    那么,既然js是异步加载,我们又该如何判断它是否加载完成呢?

    在IE或一些基于IE内核的浏览器中(如Maxthon),它是通过script节点的readystatechange方法来判断的,而其它的一些浏览器中,往往是通过load事件来决定的,如下代码:

    function include_js(file) {
        var _doc = document.getElementsByTagName('head')[0];
        var js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', file);
    if (document.all) { js.onreadystatechange = function() { if (js.readyState == 'loaded' || js.readyState == 'complete') { alert('IE6、IE7 support js.onreadystatechange'); } } } else { js.onload = function() { alert('Firefox、chrome and others support js.onload'); } } } include_js('http://static2.baihe.com/js/finallyBaiheHead.js?time=20141120');

    我们把该方法添加到body的load事件中,<body onload='dynamicLoad()'>,运行,会发现IE或Maxthon中,会弹出‘done’对话框,但是firefox或chrome中却完全没有反应,why?

    这是因为,如果script节点没有添加到DOM树中,那么在chrome和firefox中是不会响应script的load事件的。但是IE中却可以。。修改后如下代码:

    function include_js(file) {
        var _doc = document.getElementsByTagName('head')[0];
        var js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', file);
        _doc.appendChild(js);
        if (document.all) {
            js.onreadystatechange = function() {
                if (js.readyState == 'loaded' || js.readyState == 'complete') {
                    alert('IE6、IE7 support js.onreadystatechange');
                }
            }
        } else {
            js.onload = function() {
                alert('Firefox、chrome and others support js.onload');
            }
        }
    }
    include_js('http://static2.baihe.com/js/finallyBaiheHead.js?time=20141120');
  • 相关阅读:
    ubuntu 下的中文输入法的安装和配置- ibus
    数据分析-序列处理(2)
    数据分析创建数据框与数据获取(1)
    Python的函数与方法的区别
    Python3笔记015
    Python3笔记014
    Python3笔记013
    Python3笔记012
    Python3笔记011
    Python3笔记010
  • 原文地址:https://www.cnblogs.com/niubenbit/p/4110717.html
Copyright © 2020-2023  润新知