The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a solution to load the HTML with JS and CSS already applied, so it displays correctly immediately?

            $.ajax({
                type: 'POST',    
                url: service-URL,
                crossDomain : _crossDomain,
                contentType : 'text/plain',
                data:JSON.stringify(objReq),
                error:function (xhr, ajaxOptions, thrownError){
                },
                success: function(outputHTML){
                    $("#contentDiv").html(outputHTML);
                }
            }); 

Answer №1

To prevent this issue, a simple solution is to load CSS and JavaScript files in your main document.

If for any reason you do not want to load them before making an AJAX call in the main document (for instance, to speed up the initial page loading), you can utilize a nested AJAX call like the following:

$.get(resource.url, {cache:true}, function(css) {
   // Setting cache: true will utilize browser cache and load it instantly:

       $("head").append($("<link>",{
          rel: "stylesheet",
          type: "text/css",
          href: resource.url
       }));

}).then(function(){
      // You are now able to make your AJAX call here
});

Answer №2

When utilizing the html() method or setting innerHTML=, you are essentially inserting raw code directly onto your webpage. This can cause a delay as the interpreter needs to process and understand the code afterwards. Instead of this approach, you can opt to apply the content as a DOM element right from the start. One way to do this is by not passing it as plain text, or by creating a documentFragment using

document.createDocumentFragment()
. This fragment acts like an empty Node where you can add child nodes first, then append the entire fragment to the main DOM tree.

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

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

Switch the background color alternately from red to green every second

Need help with a webpage that changes the background color every second using JavaScript. The issue lies in figuring out how to correctly change the variable within the function. Here's an example of the code: <!DOCTYPE html> <html> ...

Tips for identifying if the cursor is hovering over the :before or :after section of an element

One of the challenges I am facing involves CSS and defining drop areas for users to interact with, allowing them to either drop a section before or after existing sections. .section:before, .section:after { content: "[insert here]"; height: 64px; ...

What is the method for returning a string array?

My query is about how to return a string[]. Currently, TypeScript is throwing an error because each element of the array has a type of ( T[keyof T] extends readonly (infer InnerArr)[] ? InnerArr : T[keyof T] ). How can I accept the 'property' arg ...

Updating every occurrence of a string in the visible text of a webpage: A step-by-step guide

I need to include the registered trademark symbol beside all mentions of a brand, which I'll refer to as "SomeBrand", on a client's website. Here is my current approach: function updateSomeBrand(){ var elements = document.getElementsByTagName( ...

The CSRF token is mysteriously altering in places it should remain unchanged

Implementing the code below to prevent CSRF vulnerability if (!isset($_POST['_token'])) { $_SESSION['_token'] = bin2hex(random_bytes(20)); } I then use the token in hidden inputs named _token. In my main.js file, I include the foll ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

Encountering problems with Node Sass versions while trying to import custom scss files into app.js

I've encountered several articles on stack that didn't quite solve my issues. The problem arose when I tried to import a custom SCSS file into my React app.js to override bootstrap theme colors. Here are the style imports in my App.js: import &q ...

Sending a string array from jQuery to an ASP.NET Razor website and retrieving it in the server-side code

I am working on a VS2012 website that uses razor syntax. In this website, I have several editable divs containing text paragraphs. I have enabled editing for these divs using the following jQuery code: if (cmsAuthenticated==true) $(".cmsClass").prop(&apos ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

Displaying data from a database in multiple textboxes using a dropdown list selection in ASP.NET Core MVC

I am facing an issue while trying to fetch multiple columns of data from the database using Ajax. The problem arises when I select a value from the dropdown list, and the parameter needs to pass through Ajax to the controller in order to retrieve all value ...

Can you explain the distinction between using router.METHOD() versus router.route() in Express?

There are two different ways I've come across of writing this code. router.get(path, callback) and router.route(path).get(callback) Based on the surrounding code, they seem to have the same functionality. The documentation for these methods can be ...

Substituting ng-init with scope variables results in failure

Why is nothing rendering when I try to use scope instead of ng-init in my AngularJS code below? <!doctype html> <html ng-app="myApp" ng-controller="myCtrl"> <head> <title>Bookshop - Your Online Bookshop</title&g ...

Storing Node_modules in a separate directory

All my node modules are located in the path C:/Users/user/AppData/Roaming/npm/node_modules. I am attempting to include these node modules with babel and babel-presets for my webpack scripts. Here is my webpack.config.js module.exports = { context: &a ...

When scrolling down a webpage, the background color of the content does not stretch along with the page

I've created a webpage with a sticky header and footer, along with a scrollbar on the main content. However, I'm facing an issue where the background color of the content does not extend beyond the viewport when scrolling down. The text is visibl ...

Angular Flot Chart Resizing: A Guide to Dynamic Chart S

I have successfully integrated a Flot chart into my HTML using an Angular directive. Here is how it looks: <flot id="placeholder" dataset="dataset" options="options" height="300px" width="100%" style="width:100%;" ng-disabled="graphLoading" ng-class="{ ...

Encountering a react error following the installation of FontAwesome via npm

I successfully installed fontawesome by visiting their official website and following the steps below: 1. npm i --save @fortawesome/fontawesome-svg-core 2. npm install --save @fortawesome/free-solid-svg-icons 3. npm install --save @fortawesome/react-fon ...

Issues with Header and Nav tags functionality in Internet Explorer 11 persist post deployment

When I deployed my HTML elements to the server, I encountered a problem with IE. Upon inspecting the elements in different browsers like Chrome and IE, I noticed that they appeared in the following order: <head> <link rel="stylesheet" ...

A guide on utilizing Xpath to reference a tag within a class

Trying to obtain the website link by using xpath and selenium with a reference to the class pv-contact-info__contact-type ci-websites. [Here is the html snippet being referenced][1] sel = Selector(text=driver.page_source) website = sel.xpath("//*[@class= ...