The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>:

<link rel="stylesheet" href="styles.css"> // large CSS bundle
<script defer src="main.js"></script> // small JS bundle with defer attribute

There is also a

<span id="element"></span>
on the page.

The CSS bundle includes #element { display: none; }.
The JS bundle contains (using jquery):

$(document).ready(() => {
  console.log($('#element').css('display'));
});

However, the outcome can vary. Sometimes the JS executes before the CSS, resulting in 'inline'. Other times, it executes after the CSS, yielding 'none' as desired.

To ensure that my JS bundle is non-blocking, I use the deferred attribute. Placing the JS bundle at the end of the page is not an option due to using turbolinks, which restricts this practice (source).

Using window:load isn't ideal either, as it fires once all resources are downloaded, including images.

I aim for a solution where the JS is non-blocking and executes after the CSS for consistent and predictable results. Is there a way to achieve this?

Answer №1

To ensure that a script is added to the head after a CSS file is loaded, you can use a load event handler for the link element. By doing this, the script will be dynamically inserted and automatically set as async, making it non-blocking and allowing it to execute once the CSS has been loaded.

<link id="stylesheet" rel="stylesheet" href="styles.css">

<script>
  var link = document.getElementById('stylesheet');

  link.addEventListener('load', function () {
    var script = document.createElement('script');
    script.src = 'main.js';
    document.head.appendChild(script);
  });
</script>

It's worth noting that there may be an issue if the stylesheet is cached, as it might not trigger a load event if already loaded. In such cases, you could consider checking for link.sheet.cssRules.

The reliability of load events on <link> elements has been a contentious topic in the past, so there's uncertainty about how well this approach will work consistently.

For a visual demonstration of this method, check out this CodePen showcasing JS loading with a check for link.sheet.cssRules. It has been tested and observed to function correctly in Chrome, FireFox, and Edge browsers.Link to CodePen

Answer №2

Here's a different approach I discovered. You can simply insert a script without the src attribute into the <head> section with some code, like an empty comment: <script>//</script>
That's all there is to it. Now all scripts, including deferred ones, will wait for styles to be applied.
I'm not entirely sure how this mechanism functions, but my understanding is that deferred scripts are placed in a queue after a script without a src attribute, which conventionally must wait for CSS to take effect.

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

When using the GET method to load a PHP file via AJAX, the page may not display certain jQuery plugins even after the file

Hello, I am a beginner learning AJAX and JQuery. Maybe this is a silly question, but please bear with me. I am trying to dynamically show data without refreshing the page using AJAX. I have a function loaded in the body tag which handles this. Everything ...

Ways to animate a main element independently of its counterpart's animation

I want to create an animation for a parent element without affecting the child's animation. My HTML & CSS structure is set up as follows: .parent{ background-image: url('https://pm1.narvii.com/6195/421ddbf8c9a2fb1715ef833f869164dc1be ...

Facing difficulty transferring an array from React to Django

Trying to transfer an array from the React frontend (stored in local storage) to my view class in Django is resulting in the following error: Console Output: GET http://127.0.0.1:8000/api/quiz/multiple/ 500 (Internal Server Error) Django Logs: for qu ...

Tracking page views through ajax requests on Google Analytics

I have implemented a method to log page views through ajax action when the inner page content is loaded. However, I am facing an issue where the bounce rate data is not getting updated and always shows 0%. The default Google Analytics page view is logged ...

Easily Update Your Div Content by Simply Clicking a Single Link/Button

I am in need of assistance here. My goal is to display dynamic content within a div. Below you will find the code I currently have: <script type="text/javascript"><!-- function AlterContentInContainer(id, content) { var container = documen ...

Conceal or style the filter panel in a DT datatable

Here is an example to consider: library(DT) L <- 10 datatable( data.frame( var1 = sapply(1:L, function(x) paste("<X>",paste0(x, letters, LETTERS, "\n", ...

What is the most effective way to dynamically incorporate external input into a SlimerJS script?

Could use some assistance with SlimerJS. My current program requires intermittent input from stdin to proceed with the next task. The code below functions effectively when using PhantomJS+CasperJS for reading external input, but encounters difficulties wi ...

Determine in a JSON array and add to an array object if the key is not found

I've got a JSON array like this: 0: {Id: "1", name: "Adam", Address: "123", userId: "i98"} 1: {Id: "2", name: "John", Address: "456"} The second object in the array doesn't have a userId key. How can I iterate through the array and add the ...

Implementing Ajax to Load Template-Part in Wordpress

Hey there! I'm currently working on enhancing my online store by adding a new feature. What I'd like to achieve is that when a customer clicks on a product, instead of being taken to the product page, the product details load using AJAX right on ...

Updating Button Text with PHP on WooCommerce

Hi there, I'm trying to find a way to translate a button in my WooCommerce store without using LocoTranslate or any other tools. Is there a PHP function that can help me change the button text without needing an ID? If you want to take a look at the ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

Avoiding a constantly repeating video to prevent the browser from running out of memory

Using HTML5, I created a video that loops and draws the frames to canvas. I decided to create multiple canvases and draw different parts of the video on each one. However, after some time, I encountered an issue where Google Chrome would run out of memory. ...

Error in TypeScript: The property 'data' is not found within type '{ children?: ReactNode; }'. (ts2339)

Question I am currently working on a project using BlitzJS. While fetching some data, I encountered a Typescript issue that says: Property 'data' does not exist on type '{ children?: ReactNode; }'.ts(2339) import { BlitzPage } from &q ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...

The necessary data is missing in the scope of the callback function

I'm facing an issue with a callback function's variable losing its scope. Consider the following simplified array of two objects: const search = [{socket: new WebSocket('ws://live.trade/123')}, {socket: new WebSocket( ...

Display a D3 Collapsible Tree visualization using information stored in a variable

I am currently working on an app that requires the display of a collapsible tree graph using D3. The data needed for this graph is not stored in a file, but rather within the database. It is retrieved through an Ajax call to a rest service and then passed ...

Testing React JSX components using ES6 unit tests

Currently, I am utilizing React, JSX, ES6, and Karma. I am facing an issue with my code. Can anyone pinpoint what might be wrong? I am attempting to execute a test using Karma-Runner but encountering some obstacles: let React = require("react") ...

Navigating back to the app after saving contacts can be achieved using React Native and the react-native-contacts library

I am currently utilizing the react-native-contacts library in my React Native application to save a contact. Prior to saving the contact, I request WRITE permission from Android. The process is successful; I open the contact form within my app and proce ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...

Transferring Information from Angular Interface to NodeJS through a JSON Document

I am currently working on establishing a connection between an AngularJS front end and a NodeJS back end application. The main objective is to manipulate data in a JSON file instead of a traditional database. I have attempted to set up the post method on ...