$(document).ready()启动得太早

问题描述:

所以,我需要知道一个元素的宽度与javascript,我的问题是,该函数的启动太早,宽度变化时,css被特别地应用。据我所知,$(document).ready()函数在文档完成后被触发,但似乎不起作用。

So, I need to know the width of an element with javascript, the problem I have is that the function fires too early and the width changes when the css is tottally applied. As I understood, the $(document).ready() function was fired when the document is completed, but it doesn't seem to work like that.

无论如何,我确信使用代码我的问题将被理解(这是一个简化的例子):

Anyways, I'm sure that with the code my problem will be understood (this is a simplified example):

<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <link href='http://fonts.googleapis.com/css?family=Parisienne' rel='stylesheet' type='text/css'>

    <style type="text/css">
        #target {
            font-family: 'Parisienne', cursive;
            float: left;
        }
    </style>
</head>
<body>
    <div id="target">Element</div>
</body>
</html>

<script type="text/javascript">
    $(document).ready(function(){
        console.debug($('#target').outerWidth());
        alert('hold on');
        console.debug($('#target').outerWidth());
    });
</script>

我想知道#target div的宽度,问题是在之前执行的代码该警报提供与之前不同的输出,大概是因为字体未完全加载,并且使用默认字体测量div。

I want to know the width of the #target div, the problem is that the code that's executed before the alert gives a different output than the one after, presumably because the font is not fully loaded and it's measuring the div with the default font.

它的工作原理与我预期的Google Chrome,但它不在IE和Firefox上。

It works as I expect in Google Chrome, but it doesn't on IE and Firefox.

如果您依赖外部内容已经加载(例如图像,字体),您需要使用window.load事件

If you rely on external content to be already loaded (e.g. images, fonts), you need to use the window.load event

$(window).load(function() {
    // code here
});

这些事件的行为在这篇文章