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

Creating a hierarchical visualization in Angular using a JSON object array

I'm currently working on creating a hierarchical view of users. My ultimate goal is to utilize this hierarchy view or something similar. The challenge lies in how the JSON objects used to construct the hierarchy are structured. Here's an example ...

I encountered an issue while using the tab bar feature in Bootstrap where I wasn't able to navigate back to the first tab or any

My current project involves JavaScript, and I integrated a Bootstrap tab bar component. However, when I try to run the code in Google Chrome, I encounter an issue. The first time I select the first tab, the content displays correctly. But when I select the ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

Elevation Ratio

Is there a way to make the height of the textarea in my demo always be 50% of the frame's height, even when resizing the frame? Currently, the textarea's height does not adjust dynamically. How can I achieve this? html, body { line-heigh ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Utilizing previously written HTML code snippets

While working on a page within a legacy application, I find myself repeatedly reusing a large HTML block of code. The entire HTML and JavaScript codebase is quite old. The specific HTML block in question spans over 200 lines of code. My current strategy in ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Switch the script: convert from jQuery to traditional JavaScript code

I've been trying to transition from using jQuery for a toggle script on my website to just using normal JavaScript in order to clean up the code. However, I'm having trouble converting the existing jQuery code into vanilla JavaScript. Here is th ...

What is causing my PHP script to handle NULL values when making an AJAX request?

I am facing an issue where PHP is returning NULL instead of the expected data when interacting with AJAX. Check out the relevant code snippets below: header.php <?php include_once("obtainData.php"); ?> <!DOCTYPE html> <html lang="es"&g ...

Top button disappears in Chromium browser after fade-in effect

I've encountered a very peculiar issue. Whenever I use the page down or fragmented identifier to jump to a specific div, my "go to top" image disappears. Here is the code snippet: HTML: <a title="Go to top" href="#" class="back-to-top"></ ...

Concealing the footer on a webpage embedded within an iframe

<script> $(document).ready(function(){ $('.mydivclass').hide(); }); </script> Looking to embed Microsoft Forms in my HTML using an iframe. Can the footer of the Microsoft Forms be removed? ...

Dealing with Ajax errors in Django reponses

My code includes an ajax call to a Django view method: $("#formi").submit(function(event){ event.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ type:"POST", url ...

Can anyone recommend a lightweight Ajax Engine that can be developed using C# and ASP.Net? I need something that is adaptable and efficient

Previously, I developed a quick Ajax Framework for a project involving an ASP.Net Website (C#). Since there weren't many Ajax functions required, I created a new blank page and added code to the Page_Load method in the code behind file. This code woul ...

Tips for transforming an html form into an ajax request for a rest controller when dealing with a multi-select field

I am encountering an issue with the field "roles" as it is a select list with multiple choices. I need to convert this field into an array, but I have not been able to find any information on how to do so. Any assistance would be greatly appreciated. Thi ...

Utilize JavaScript and PHP to dynamically modify the contents of an HTML file

After not receiving a satisfactory answer to my question yesterday, I decided to find a solution. However, I am now facing an issue with the new program and unsure of the mistake. The program involves retrieving the contents of announcement.html and displ ...

Menu within a menu, accessed by hovering

<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a href="index.html" class="navbar-brand display-4">NintendoWorlds</a> <button class="navbar-toggler" dat ...

"Dynamic" visual in a Vue.js development scheme

Utilizing Vue.js for the development of a hybrid mobile application has been my current focus, with the Quasar framework serving as a key component. Recently, I incorporated an image into the application using the <img /> tag and utilized the followi ...

checkbox-activated navigation bar

Struggling to implement a Nav-drawer that should open when a checkbox is selected, everything seems to be set up correctly but the issue arises when it comes to actually opening it. Here is the code snippet: <div class="leftside"> <input typ ...

Receiving a 500 status code upon converting a SqlDataReader into Json format

Getting a status 500 error and not sure where I am going wrong. When I click on the 'Getcustomers' button, the 'GetCustomers' method is called which returns JSON. Script: <script> var MyApp = angular.module("MyApp", []); ...

HTML text-indent is a way to add extra space to

I cannot understand why my text is not indenting properly. At the very bottom left corner, the "Educational Specifications" text is enclosed within a p element as follows: <p style="text-indent: 3em">Educational Specifications</p> Why doesn& ...