Ensure that the Javascript file is included before the CSS file to prevent any margin

I have external files for JavaScript and CSS. According to This question, they suggested that including JavaScript before CSS could enhance performance. However, I noticed a discrepancy in Chrome when I load JS before CSS - the .offset() function returns a different value. Here is the structure of my 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;
}

You can view the test page at

The layout appears correct on all browsers, but there are variations in the values returned by offset().left. In IE and Firefox, it shows 200, while in Chrome, it displays 8. The version of Chrome being used is 41.0.2272.118m. After asking friends to check, they encountered the same issue. However, changing the order of CSS and JS resolved the discrepancies, with all browsers returning 200. It seems like the $(function(){}) behavior in Chrome may not be as expected. Did I misunderstand something? Is it advisable to avoid placing JS before CSS? Thank you!

Answer №1

When using jQuery, $(function() { }); is essentially the same as:

 $( document ).ready(function() {
  // This code will run once the DOM is ready
});

Sometimes in Chrome, the JavaScript file may execute before the CSS has finished parsing, leading to incorrect offsets. To ensure all elements are loaded properly, you can modify your JavaScript like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

Issue with the appearance of the footer in my Wordpress template

After creating a WordPress template, I noticed that the footer is not extending to 100% width as expected. Check out the page here Any suggestions on why this might be happening? Could it be due to a missing closing div tag somewhere in the code? Thank ...

How to temporarily change CSS color for 5 seconds using JavaScript and incorporate an easing effect?

Regarding this query: JavaScript - Modifying CSS color for 5 seconds Here is a live example of the solution: http://jsfiddle.net/maniator/dG2ks/ I am interested in adding an easing effect to the transition, gradually making the color fully opaque and t ...

What is the process of creating a Listbox that is initially empty and allowing options to be passed without automatically selecting

When designing my form, I encountered an issue with moving categories from one listbox to another. Here's how I tackled the problem: The bottom box serves as the "input" box that is read on the server side when the form is submitted. This is how I ge ...

Having trouble displaying values from nested JSON in a datatable

Response from server : ["{\"CLIENT\":[{\"tranche\":\"1-4\",\"prix\":\"65.96\",\"currency\":\"E\"}],\"DISTRIBUTEUR\":[{\"tranche\":\"1-4\",\"prix\ ...

selenium.common.exceptions.WebDriverException: Error: Chrome encountered an issue while attempting to launch and exited unexpectedly

Here is the code snippet: import os from selenium import webdriver chromedriver = "/usr/bin/chromedriver" os.environ["webdriver.chrome.driver"] = chromedriver driver = webdriver.Chrome(chromedriver) driver.get("http://stackoverflow.com") driver.quit() To ...

Reorganize elements using CSS styling

I have a trio of child divs with the classes span2, span7, and span3. When my browser width drops below 763px, I want them to display in the order span2, span3, and span7. How can I achieve this using CSS? Here is the code snippet I started with: <div ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Is it feasible to grant Ajax authorization to a website that is not within the same origin?

I am attempting to extract a particular p element from one of my websites hosted on Server 1 and place it within a <div id="insert"></div> element located on a website hosted on Server 2 I'm striving to achieve this through the use of t ...

Adaptable bootstrap placement

I have created a form that includes a custom checkbox element. The issue is that the label for the checkbox is not vertically aligned with the checkbox itself. How can I adjust the label to be vertically centered with the checkbox? You can see the code ...

Harness the power of JQuery by linking various triggers from different elements to a single event

I have been scouring the depths of the internet in search of a solution to this specific problem, but all I seem to find are variations on similar elements and events. The issue at hand is that I have a search button that toggles the visibility of the sea ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

When adjusting to mobile dimensions, the responsive website design struggles to center the navbar properly

I am currently developing my senior year portfolio website and I am struggling to center the navbar (Work About Contact) when it is in mobile mode. My goal is for it to be positioned directly below the logo, perfectly centered, but so far nothing I have tr ...

Creating an Unordered List in GWT that Includes List Items

I've hit a roadblock while trying to create a css-driven menu in GWT. The menu should be rendered exactly like this: <div class="topbar"> <div class="container fixed"> <h3> <a href="" class="logo">test& ...

Tips for preventing the repeated loading of external libraries: Leveraging npm packages, using browserify, and strategically implementing script tags

I have developed a single-page web app using jQuery along with another library and a bundle.js created with npm and browserify. The bundle.js also relies on the same libraries. My architecture works like this: On the HTML page, I load certain functiona ...

Tips for effectively utilizing innerHTML in this particular scenario

For an assignment, we were tasked with creating a Madlib game where users input words into textfields to replace certain words in a hidden paragraph within the HTML using JavaScript and CSS. The paragraph embedded in the HTML page is as follows: <span ...

Easily iterate through the <li> elements using jQuery and append them to the <datalist> dynamically

My jQuery loop seems to be malfunctioning as it's not showing the values of my li elements. Instead, I'm seeing [object HTMLElement] in my input search bar. <div id="sidebar-wrapper"> <input type="text" list="searchList" class="searc ...

Full-width header with scrollable content within the viewport

Is there a way to make the header and footer expand to 100% width while keeping the middle content width variable? You can view the source at http://jsfiddle.net/9dWcZ/ HTML: <div class="header"> this is header </div> <div class="content ...

Using JavaScript to implement CSS3 with multiple background images

Is there a way to programmatically define multiple background images in CSS3 using JavaScript? While the common approach would be: var element = document.createElement( 'div' ); element.style.backgroundImage = "url('a.png') 0 100%, ur ...

100% width is applied to the table cell within the div element

Below is the code I am working with: <div style='display: table'> <div style='height:200px; width:100%; text-align: center; display: table-cell; vertical-align: middle'>No result found</div> </div> I'm ...