Professional JS(HTML5 Event/Device Event[part])

本文详细介绍了多种网页生命周期事件,包括beforeunloadEvent、DOMContentLoadedEvent、readystatechangeEvent等,解释了它们的作用及应用场景,并给出了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.beforeunload Event
+①window对象上的beforeunload事件,是为了让开发人员有可能在页面卸载之前阻止这一操作。IE,Firefox,Safari,Chrome和Opera 11+支持这个该事件,

EventUtil.addHandler(window,'beforeunload',function(event){
    event=EventUtil.getEvent(event);
    var message="l'm really going to miss you if you go.";
    event.returnValue=message;
    return message;
});

2.The DOMContentLoaded Event
①The window's load event fires when everything on the page has been completely loaded,which may take some time for pages with lots of external resources.The DOMContentLoaded event fires as soon as the DOM tree is completely formed and without regard(关心) to images,JavaScript files,CSS files,or other such resources.

+②To handle the DOMContentLoaded event,you can attach an event handler either on the document or on the window(the target for the event actuallt is document,although it bubbles up to window).

EventUtil.addHandler(document,'DOMContentLoaded',function(event){
    alert('Context loaded');
});

③The event object for DOMContentLoaded doesn't provide any additional information(target is document).

④The DOMContentLoaded event is supported in IE 9+,Firefox,Chrome,Safari 3.1+,and Opera 9+ and is typically used to attach event handlers or perform other DOM manipulations.This event always fires before the load event.

+⑤For browsers that don't support DOMContentLoaded,it has been suggested that a timeout should be set during page loading with a millisecond delay of 0.

setTimeout((function){
    //attach event handlers here
},0);//0毫秒

3.The readystatechange Event
+①IE为DOM文档中的某些部分提供了readystatechange事件,用于提供与文档或元素的加载状态相关的信息。

EventUtil.addHandler(document,'readystatechange',function(event){
    /*
    支持readystatechange事件的每个对象都有一个readyState属性:
    1.undefined:对象存在但并未初始化。
    2.loading:对象正在加载数据。
    3.loaded:对象加载数据完成。
    4.interactive:可以操作对象,但还没有完全加载。
    5.complete:对象已经加载完毕
    */
    if(document.readyState == 'interactive'){
        alert('Content loaded');
    }
});

+②当交互阶段与完成阶段无法确定顺序时,同时检测这两个阶段。

EventUtil.addHandler(document,'readystatechange',function(event){
    if(document.readyState == 'interactive' || document.readyState == 'complete'){
        EventUtil.addHandler(document,'readystatechange',arguments.callee);
            alert('Content loaded');
    }
});

+③The readystatechange event also fires on <script>(IE and Opera) and <link>(IE only),allowing you to determine when external JavaScript and CSS files have been loaded.

EventUtil.addHandler(window,'load',function(){
    var script=document.createElement('script');
    script.type='text/script';
    //为新创建的<script>节点指定了一个事件处理程序
    EventUtil.addHandler(script,'readystatechange',function(event){
        event=EventUtil.getEvent(event);
        //该事件的目标是节点本身
        var target=EventUtil.getTarget(event);
        //当触发readystatechange事件时,需要检测目标的readyState属性是否等于"loaded"或"complete"
        if(target.readyState == 'loaded' || target.readyState == 'complete'){
            //如果进入其中任何一个阶段,则移除事件处理程序(以防执行两次)
            EventUtil.removeHandler(target,'readystatechange',arguments.callee){
                alert('Script loaded');
            };
        }
    });
    script.src=example.js;
    document.body.appendChild(script);
});


EventUtil.addHandler(window,'load',function(){
    var link=document.createElement('link');
    link.type='text/css';
    link.rel='stylesheet';

    EventUtil.addHandler(link,'readystatechange',function(event){
        event=EventUtil.getEvent(event);
        var target=EventUtil.getTarget(event);
        if(target.readyState == 'loaded'|| target.readyState == 'complete'){
            EventUtil.removeHandler(link,'readystatechange',arguments.callee){
                alert('CSS loaded');
            };
        }
    });
    link.href='example.css';
    document.getElementsByTagName('head')[0].appendChild(link);
});

4.The pageshow and pagehide Events
①Firefox and Opera introduced a feature(特性) called the back-forward cache(bfcache) designed to speed up page transitions when using the browser's Back and Forward buttons.The cache stores not only page data but also the DOM and JavaScript state,effectively keeping the entire page in memory.If a page is in the bfcache,the load event will not fire when the page is navigated to.This usually doesn't cause an issue since the entire page state is stored.However,Firefox decide to provide some events to give visibility to the bfcache behavior.

+②The first event is pageshow,which fires whenever a page is displayed,whether from the bfcache or not.On a newly loaded page,pageshow fires after the load event;on a page in the bfcache,pageshow fires as soon as the page's state has been completely restored.Note that even though the target of this event is document,the event handler must be attached to window.

(function(){
    var showCount=0;

    EventUtil.addHandler(window,'load',function(){
        alert('Load fired');
    });

    EventUtil.addHandler(window,'pageshow',function(){
        showCount++;
        alert('Show has been fired ' + showCount +' tiems.');
    });
})();

(function(){
    var showCount=0;

    EventUtil.addHandler(window,'load',function(){
        alert('Load fired');
    });

    EventUtil.addHandler(window,'pageshow',function(){
        showCount++;
        //pageshow事件的event对象还有个persisted的布尔值属性,如果页面被保存在了bfcache---true
        alert('Show has been fired ' + showCount +' times. Persisted? '+ event.persisted);
    });
})();

+③与pageshow事件相对应的是pagehide事件,该事件会在浏览器卸载页面的时候触发,而且是在unload事件之前触发。

EventUtil.addHandler(window,'pagehide',function(event){
    alert('Hiding. Persisted? ' + event.persisted);
});

④支持pageshow和pagehide事件的浏览器有Firefox,Chrome,Opera,Safari 5+ 和IE 9+.

?⑤指定了onunload事件处理程序的页面会被自动排除在bfcache之外,即使事件处理程序是空的。因为,onunload最常用于撤销在onload中所执行的操作,而跳过onload后再次显示页面很可能会导致页面不正常。

5.The hashchange Event
①HTML5新增了hashchange事件,以便在URL的参数列表(URL中”#”后面的所有字符串)发生变化时通知开发人员。增加这个事件的原因是为了在Ajax应用中,方便开发人员通过URL参数列表来保存状态或导航信息。

+②必须要把hashchange事件处理程序添加给window对象,然后URL参数列表只要变化就会调用它。此时的event对象会额外包含两个属性:oldURL和newURL。

EventUtil.addHandler(window,'hashchange',function(event){
    alert('Old URL: ' + event.oldURL + '\nNew URL '+ event.newURL);
});

+③支持hashchange事件的浏览器有IE 8+,Firefox 3.6+,Safari 5+,Chrome和Opera 10.6+。只有Firefox 6+,Chrome,Opera支持oldURL和newURL。因此,最好使用location对象来确定当前的参数列表。

EventUtil.addHandler(window,'hashchange',function(event){
    alert('Current hash: '+location.hash);
});



//检测浏览器是否支持hashchange事件

//这里有个bug,如果IE8是在IE7文档模式下运行,即使功能无效也返回true
var isSupported=('onhashchange' in window);

//更为稳妥的检测方式
var isSupported=('onhashchange' in Window) && (document.documentMode===undefined ||
    document.documentMode>7);

6.Device Event
+①orientationchange事件,用于了解何时用户由横向查看切换为纵向查看模式。

EventUtil.addHandler(window,'load',function(event){
    var div=document.getElementById('myDiv');
    div.innerHTML='Current orientation is '+window.orientation;
    EventUtil.addHandler(window,'orientationchange',function(event){
        div.innerHTML='Current orientation is '+window.orientation;
    });
});

another:
①encodeURI/encodeURIComponent/decodeURI/decodeURIComponent

②URI&URL&URN
http://www.cnblogs.com/wuyun-blog/p/5706703.html
a)URI可以分为URL,URN或同时具备locators和names特性的一个东西。URN的作用就像一个人的名字【身份】,URL就像一个人的家庭住址【如何找到它】。
b)Uniform Resource Identifier/Locator/Name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值