2

I have an external JavaScript file and Css file. In This question,they said that including Js before Css may improve performance. But if I load JS prior to Css, Chrome returns a different value when I call .offset() function. The HTML file:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="script/jquery.js"></script>
<script type="text/javascript" src="script/divtest.js"></script>
<link rel="stylesheet" type="text/css" href="css/divtest1.css"/>
<title>TEST</title>
</head>
<body>
<div id="canvas">
hello
</div>
<div id="msg">
</div>
</body>

JavaScript file:

$(function(){
var margin;
margin=$('#canvas').offset().left;
$('#msg').html(margin);
});

Css file:

*{
margin:0px;
padding:0px;
}
#canvas{
margin-left:200px;
background-color:red;
width:300px;
height:300px;
}

The test page is on http://me.lzu.edu.cn:8080/work/divtest

It looks fine in all browsers, but when I call offset().left, they return different values. In IE and Firefox, it returns 200, but in Chrome, it returns 8. Chrome Version is 41.0.2272.118m. I've asked somes of my friends to test this page and get the same answer. But if I put Css before JS, all of them return 200. It seems that in Chrome, $(function(){}) does not work as expected. Do I misunderstood somethings? Should I stop putting JS before Css? Many Thanks!

Community
  • 1
  • 1

1 Answers1

1

The jQuery $(function() { }); is equivalent to:

 $( document ).ready(function() {
  // wait for dom to be ready before executing code here
});

Chrome is executing the javascript file and occasionally returning the offset before the css has been parsed. You could try waiting for the complete window object to ensure all sub elements are loaded by changing your javascript file to:

$(window).load(function() {
  var margin;
  margin=$('#canvas').offset().left;
  $('#msg').html(margin);
});
RepeatQuotations
  • 635
  • 5
  • 10