javascript - Wrong dimensions retrieved from div on first page load -


i using robotto monospace font , need calculate single characters width.so doing

var singlecharacterwidth;    function calculatecharacterswidth() {    var x = $('<div>').text('a').appendto('#hiddenview');    singlecharacterwidth = x.width();    $('#hiddenview').empty();  }    $(document).ready(function() {    calculatecharacterswidth();        console.log(singlecharacterwidth);  });
#hiddenview {    float: left;    font-family: 'robotomono-regular';    font-size: 12px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>  <link href="https://fonts.googleapis.com/css?family=roboto+mono" rel="stylesheet">  <div id="hiddenview"></div>

when page loads first time gives wrong width , after reloading page gives proper width.

first time page loading calculatecharacterswidth() gives 9. on reload gives proper character width i.e 7.20

what's wrong this?

screenshot of console

enter image description here

this doesn't happen when use default monospace font.it returns same width.
so related loading of custom font..

possible duplicate of post : jquery width() incorrect after document ready?

the idea move function call $(window).load() event instead of document ready !

it solved issues many times, hope it'll you


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -