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>
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.
It works as I expect in Google Chrome, but it doesn't on IE and Firefox.
Approach 1: Using the holdReady() method in the jQuery library and the setTimeout() method. First we set the parameter in the holdReady() method to true to hold the execution of the document. ready() method. Then, a timeout function with an appropriate delay time can be added using the setTimeout() method.
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
jQuery $(document). ready() Equivalent in JavaScriptThis event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
If you rely on external content to be already loaded (e.g. images, fonts), you need to use the window.load event
$(window).on("load", function() { // code here });
The behaviour of these events is described in this article:
There is [a] ready-state however known as DOM-ready. This is when the browser has actually constructed the page but still may need to grab a few images or flash files.
Edit: changed syntax to also work with jQuery 3.0, as noted by Alex H
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With