开发者

jquery(document).ready() fails to run in IE 7+

This seems like really simple problem to me, but despite googling every possible search string, I cannot find an answer.

I'm using jquery 1.5.1 and trying to开发者_Go百科 use the $(document).ready() function to bind several click events when the page loads. Eventually I narrowed down the problem to be this small:

$(document).ready(function(){
    alert('hello world');
});

In IE 6,7, and 8 I never see the hello world alert when I load the page. IE 9 works though, as does FF, Chrome, Safari etc.

A solution that sort of worked was to surround the alert in a 500ms JS timeout. This only seems to work sometimes but definitely not consistently enough.

The only possibility I can think of is that because this script happens to be loaded well inside the body tag of the page HTML, this might be messing up the ready() function. If that's the case, I don't know what the solution would be.

UPDATE

OK, after testing a smaller page I can get the document ready to work in IE (no alerts though, I guess that's a completely different problem).

Are there any quirks regarding IE in terms of where you can load the javascript files in the page?


What do you have in the type="" attribute? IE is very strict when it comes to that attribute. If you specify that attribute, it must contain "text/javascript" or else IE will ignore it.


There's no reason to use $(document).ready inside the BODY of the page. Use it when your SCRIPT tag is in the HEAD of the page, or else remove it and don't add your SCRIPT tag until after all the necessary body elements are closed.


Do you have any other javascript files that could be conflicting with the jQuery $?

Conduct a test when the page loads,

if (typeof jQuery == 'undefined') {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'js/jquery/1.4.4/jquery.min.js';
        document.getElementsByTagName('head')[0].appendChild(script);
        setTimeout(checkjQuery, 0);
    }
    function checkjQuery() {
        if (typeof jQuery == 'undefined') {
            setTimeout(checkjQuery, 0);
        } else {
            jQuery.noConflict();
        }
    }; 


So after messing with this I'm arriving at the conclusion that the IE browsers I'm using in a VM are at fault. The failure of the buttons and ajax calls to work correctly seems to be random and intermittent regardless of changes I make to the javascript. I think the document ready had been working all along and the browsers were failing in different ways. It seems to be working now.


I've had this problem with IE7, it seems that I was using

<script type='application/javascript' language='javascript'>
$(document).ready(function() { ... })
</script>

Changing the first script tag to

<script type='text/javascript' language='javascript'>

Seems to make it work. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜