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

Incorporating HTML into the Ajax Response

I recently encountered a strange issue with a service that returns an HTML page as the AJAX response. This page contains a form that is automatically triggered by scripts within the page, resulting in a POST request being sent when the page is rendered. My ...

Struggling with pagination problems in Bootstrap 4 and looking to integrate QR code functionality into your blade template?

I am currently facing an issue with generating a batch of QR codes using the SimpleQR code generator in Laravel blade template on the fly for printing. The problem arises when a page break occurs, as it breaks the QR code. I attempted to use the break-insi ...

Rendering the HTML5 canvas within a console environment

I am looking to create images of humans on the console using nodejs. In order to achieve images of higher quality, I require a library or module that can facilitate drawing images in the console. Some options available include imaging and console-png. How ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

Another option in place of MicrosoftAjax using JQuery

Currently, I am utilizing <script src="../../Scripts/MicrosoftAjax.js"></script> <script src="../../Scripts/MicrosoftMvcAjax.js"></script> <script src="../../Scripts/jquery-1.8.3.js"></script> However, the MicrosoftAja ...

Troubleshooting Routing Issues in a Next.js Website Tutorial

After going through the next.js tutorial at https://github.com/zeit/next-learn-demo.git, I encountered an issue starting from stage 3 "dynamic routing". Despite the tutorial indicating that dynamic routing should be working from stages 3 to 8, it wasn&apos ...

Tips for obscuring URLs in AngularJS code without relying on base 64 encoding or Gulp obfuscation techniques

I'm looking for a way to obfuscate specific URLs in my AngularJS code without using base 64 encoding. Is there a method to only obfuscate URLs? var app_data = { 'APP_CONFIG': { 'USER_URL': 'http://127.1.1.0:8000/ ...

Executing jQuery code after a data update in Angular can be achieved by utilizing

Currently, I am working with Angular 1.4.7 on a site that was not set up by me. As a result, I am uncertain about the specific information needed in this scenario. We are displaying search filters, but their enabling or disabling is controlled by data fetc ...

What is the process for extracting JSON values by specifying keys within a nested JSON structure?

I am attempting to extract specific JSON values for particular keys from a JSON structure. I have made the following attempt: var jsonstring; jsonstring = JSON.stringify(myjsonObjectArray); alert(jsonstring);//displaying the JSON structure below jsonstri ...

Utilizing Jquery's each() method to retrieve the exact position of a specific class element

Is there a way to determine the position of the "owl-item active" element? The current position is 2 out of 3 total photos. <div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage"> ...

Guide to creating AngularJS directive attributes without a right-hand side in hiccup code?

I'm currently developing an AngularJS application using markup in hiccup format. Here is a snippet of the markup: <div modal-show modal-visible="showDialog" .........></div> Below is the corresponding Hiccup I have created: [:div.modal. ...

Is it possible to center-align the text in a Material-ui TextField and enforce a minimum numerical value at the same time?

I'm facing an issue with trying to center align the text inside the TextField and also set a minimum value of 0. It seems like I can only achieve one or the other, but not both simultaneously. I referred to the material-ui page on TextField for help, ...

Removing unexpected keys during validation using Joi

Within my server-side JavaScript code, I am utilizing Joi for validating a JavaScript object. The schema being used is structured as follows: var schema = Joi.object().keys({ displayName: Joi.string().required(), email: Joi.string().email(), e ...

What are the most effective methods for utilizing React child components?

I have a particular interest in how to efficiently pass information along. In a different discussion, I learned about the methods of passing specific props to child components and the potential pitfalls of using <MyComponent children={...} />. I am ...

Methods for concealing the title and date when printing web content using JavaScript

When utilizing the window.print method to print out a specific screen, I encountered an issue. I need to hide the date in the top left corner of the image as well as the title (not the big heading) which has been intentionally blurred. I've come acro ...

Enhance the language with react-intl and MobX State Tree integration

Currently, I am integrating react-intl with Mobx state tree for the first time. Within my project, there are two buttons located in the header section - one for 'it' and the other for 'en'. Upon clicking these buttons, the selected lan ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

Submit field values only once the form has been confirmed to be validated

My current project involves using AJAX to submit form values, with the added requirement of implementing form validation. If any field in the form is empty, the submission should be prevented. I'm facing a challenge in figuring out how to halt the for ...

Utilize PHP to populate grouped tables and filter them using jQuery through AJAX with JSON

There are two PHP files in play here. The first one, fetch.php, creates a filtered array (filtered from leagueboxes.php) and then sends it back to leagueboxes.php via Ajax JSON. fetch.php <?php include_once 'dbconfig.php'; if(isset($_GET[ ...

Changing the size of shapes in cytoscape.js when using the dagre layout

My goal is to resize the shapes of the nodes based on the size of the node text. I tried following the steps outlined in https://github.com/cytoscape/cytoscape.js/issues/649, but encountered some issues: The shapes consistently end up with equal height a ...