Ways to postpone CSS and Script loading once JavaScript has been executed

My issue with my backbone.js app is that I have noticed some slow loading files (a .css and a .js) that are causing the page to block until they are fully loaded.

After rendering the backbone view, I am looking for a way to delay the loading of these files until after certain JS has been executed. I have attempted to achieve this in JS with the following code:

view.render()
$('head').append("<script type=...")
$('head').append("<link rel='stylesheet'...")

While this solution works, I have encountered an issue with my CSS (specifically a webfont css) where the page fonts are hidden on Android phones and only appear when the screen is touched.

My question is, is this method of loading CSS and JS after page load considered a poor practice? Are there alternative, more effective approaches to consider?

Answer №1

Learn how to dynamically add a script file using JavaScript

if(conditionIsMet){
    // fetch script from server
    $.getScript( "serverPath/script.js", function( data, textStatus, jqxhr ) {
        // perform actions upon successful load
    });
}

Answer №2

The main issue at hand is identifying why your JavaScript and CSS files are loading slowly. Is it due to an excessive amount of code within the files, or perhaps they are referencing resources on external sites that are causing delays in loading? If you can optimize these files to improve their loading speed, it would be ideal to load them in the <head> section of your web page.

One potential solution could be to split your stylesheet into two separate parts. Place webfont declarations and essential CSS in a small file that loads at the beginning of the page, while additional optional CSS rules can be placed in a second file that loads after the page has been rendered.

However, I would advise against loading CSS rules after the page has already been rendered. This approach could lead to elements on the page shifting around, especially if you have specified positions or sizes in your CSS rules. It is best practice to load CSS before the page is rendered to prevent users from experiencing visual inconsistencies as the browser processes and displays your CSS rules.

Answer №3

The asynchronous loading of CSS is not the issue here; it's actually the JavaScript causing the problem.
Ideally, you should place the JavaScript at the bottom of your page. However, you can also place it in the head or body to prevent it from blocking rendering by adding an async attribute:

< script type="text/javascript" async src="your path">< /script>
If you have multiple files that rely on each other, you can use the async defer attribute like this:
< script type="text/javascript" async defer src="your path">< /script>
< script type="text/javascript" async defer src="your path">< /script>
These files will be executed asynchronously in the specified order after loading.
For more information, you can refer to this link:
http://www.w3.org/TR/html5/scripting-1.html#attr-script-async

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

Javascript onclick events failing to toggle video play/pause functionality

In my website, I have background music and a background video (webm format) embedded. I am facing an issue with making play/pause buttons in the form of png images work for both the video and the music. The background music is added using the embed tag wi ...

Tips for expanding the HTTP header size within Next.js

Can someone provide assistance for increasing the HTTP header size in my Next.js app? The current size is set at 16384 and I am unable to execute the necessary command node --max-HTTP-header-size=24576 server.js. Looking for help from someone with more e ...

Updating JavaScript alert title in Android webview: A guide for developers

I have integrated a web view in my Android application, which contains a button. When the button is clicked, it triggers a JavaScript function that displays an alert box with the title "The page at 'file://' says". I would like to customize this ...

Creating Visuals with CSS Gradients: A Tutorial on Generating Images and SVG Files

I currently have a CSS gradient applied and I am interested in creating an image or SVG file from it. However, I am unsure of how to accomplish this task. Any advice would be greatly appreciated. background: -webkit-linear-gradient(bottom, rgb(211, 208, ...

Adjust the PHP variable's value when loading content via AJAX

Seeking assistance after attempting to create a PHP template within the Foundation 4 framework without clear guidance. The framework is quite basic, so I used jQuery to incorporate page transitions by making an AJAX call to retrieve "content" from another ...

Creating Your Own Custom Select with DataTables

Hey there! I’m currently utilizing the tablesorter-plugin DataTables with serverside processing and ajax pipelining. Here’s a glimpse of my present serverside script: <?php // Database table being used $tabl ...

Resetting form fields when clicking the "Next" button with the FormToWizard jQuery Plugin

I am in the process of developing a lengthy form using the jQuery plugin called formToWizard. Within one of the fieldsets located midway through the form, there are hidden fields that are displayed upon clicking a button. The strange issue I am encounterin ...

What is the best way to access the current Google account signed in on an Android device using jQuery and Cordova?

Is it possible to retrieve the currently logged in Google account on Android devices using jQuery and Cordova? $(function(){ $('#LoginForm').submit(function(){ var loginData = $ ("#LoginForm").serialize(); ...

Is there a way to customize the pagination layout of primeNG paginator in an Angular project

I've been struggling to customize the primeNG paginator in my Angular application. Specifically, I am trying to style the dropdown that lets users select the number of data entries. Despite my efforts to figure it out, I have not been successful in st ...

Please refer to the appropriate manual for your MySQL server version to find the correct syntax for the following statement: `'' , , '', '', '', '', '', '', NOW())' at line 2`

I encountered an error and since I am new to programming, I would appreciate any corrections. Thank you! <? $customername = $_REQUEST["customername"]; //$customername = strtoupper($customername); //$customername = trim($customername); $address1=$_RE ...

Trigger jQuery event when the value of a select element changes, with the exception

On my page, there are numerous select buttons. I am seeking a way to trigger a jQuery function whenever any select button changes, except for the one with id="Select1". While I understand that I can directly link the function to each desired select button, ...

Passing a variable in an AngularJS $http.get() call to retrieve a specific section of a JSON data file

Currently, I am using json files to stub my $http.get() calls. I am trying to retrieve a specific subset of the json file in my angular controller. Despite looking at other solutions that recommend setting a params property in the Get call, it does not see ...

Loop through the elements retrieved by the `getElementsByName` method in

My goal is to access each node by elementName using the following JavaScript code: function myFunction() { var h1 = document.getElementsByName("demoNode"); for (var i = 0; i < h1.length; i++) { if (h1[i].name == "demoNode") { var att ...

Initiating a server call to fetch data using jQuery's AJAX function

I need to create a simple AJAX request to check if a username already exists in the database. The challenge lies in the JavaScript function that sends the request: function usernameCheck(){ $.post("http://example.com/signup", {username: $("#username"). ...

`Enhance Image with a Fresh Hue`

Let me explain my dilemma: I'm dealing with a two-tone png image - one tone is black and the other is transparent. Right now, I'm relying on the background color attribute to dynamically change the color of the transparent section. However, I ...

Tips for creating visually appealing tables in ReactJS

For my school project, I need to create a table using ReactJs. I have already created the table but it needs improvement in terms of design. However, I am unsure how to modify my code to achieve the desired look. I tried looking on YouTube for tutorials, b ...

Colorbox offers the ability to display or mimic a 'loading' animation for content that is displayed inline

Hello! I am currently utilizing ColorBox and implementing a few steps in a form using jQuery. We are looking to display the loading animation of ColorBox while waiting for responses from AJAX requests. Could you please provide guidance on how we can ac ...

Vuetify Error - "Attempting to access 'extend' property of an undefined object"

Upon installing Vuetify, I encountered an error in the console. My webpack version is v3.6 Uncaught TypeError: Cannot read property 'extend' of undefined at Module../src/mixins/themeable/index.ts (index.ts:21) at __webpack_require__ (boo ...

contrasting ionic and android software development kits

I am interested in developing an android application and have some knowledge about Ionic, which is also used for creating mobile apps. I have more experience with Android development and am curious to understand the distinctions between the two platforms ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...