execute JavaScript function once every script on the webpage has been completely loaded

I want to execute a basic javascript function once my webpage has fully loaded. Here's an example of the function:

<script type="text/javascript">
function changeSize() {
  var el = document.getElementById("my-id");
  el.style.height = "500px";
};
</script>

My webpage contains a lengthy (takes seconds) script fetched from an external URL that generates the main content within the html body.

I am utilizing Bootstrap and the body section in my base.html looks like this:

<body>

  <div class="container-fluid">
    {% block header %}{% endblock %}

    {% block content %}{% endblock %}

    {% block footer %}{% endblock %}

  </div>

  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>

The content block is imported from an external html file as shown below:

{% extends 'base.html' %}

{% block header %}
{% include 'header.html' %}
{% endblock %}

{% block content %}
  <div class="my-class" id="my-id">
        {{ myapp | safe }}
  </div>
{% endblock %}

{% block footer %}
{% include 'footer.html' %}
{% endblock %}

Within the 'my-id' element, myapp is populated by the long-loading js script which, upon completion, displays all page content. The external URL path for myapp is defined and retrieved via a python script using Flask.

I have attempted window.onload = changeSize;,

<body onload="changeSize();">
, and monitored the timing of all stages in document.readyState.

All these methods trigger my js function after the html has fully loaded, but before the external script for myapp finishes. How can I detect when all elements and scripts have completely finished loading?

Answer №1

After experimenting with different approaches, I finally found a solution involving a delay method that was inspired by an answer on Stack Overflow (referenced here).

To implement this solution, create a new file named custom.js and add the following code:

function delay() {
    setTimeout(function() {
        changeSize();
    }, 200);
}

if (document.readyState == 'complete') {
    delay();
} else {
    document.onreadystatechange = function () {
        if (document.readyState === "complete") {
            delay();
        }
    }
}

Next, include the custom.js file in your base.html using the following script tag:

<script type="text/javascript" src="{{ url_for('static', filename='custom.js') }}"></script>

This implementation effectively waits for the lengthy loading process to complete before triggering the changeSize() function.

Answer №2

I'm uncertain about the process of loading external scripts. If they are loaded using a special library, it may be necessary to wait for a callback before initializing your App.

Alternatively, you might consider utilizing the DOMContentLoaded event. This could potentially provide a solution, if my understanding is correct.

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM fully loaded and parsed");
});

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

The route does not support the POST method

I am currently working with Laravel version 6.18.22 and have been able to successfully add and edit staff records using jQuery and AJAX. The issue I am facing is that after clicking the submit button on the modal form, I can insert or edit the data success ...

jQuery's conditional always evaluates the first condition

One of the elements in my jQuery code is a conditional function designed to display a specific message with its own style when necessary: function msg(type, text) { if (type="success"){ $('.messageDisplay').attr('class', &a ...

Guide on making a half circle within a container or a button aligned with text

I'm struggling with designing a half circle inside a button that is centered inline with the text. Can someone please assist me with this? On this particular scenario, what would be more suitable - using a button element or styling a div to look like ...

Graphql query using $http.post is unsuccessful

I successfully made a request for the code below, but I am encountering an issue where I am not receiving any data back. The "preview" tab of the request in Chrome simply displays "Error Not Found". Interestingly, when I try the same query in GraphiQL, i ...

Establishing a connection between the socket and the currently authenticated user through socket.io

My website consists of multiple pages, and when a user logs in, I need to establish a connection between their user ID (stored in MongoDB) and the socket for real-time messaging. Currently, user details are saved in the express session variables upon login ...

I have been attempting to extract real estate listings from an MLS website using Beautiful Soup and have found some success. I am now considering if using Selenium would be a more efficient option

Perhaps this question has been answered before, which could help guide me in the right direction. The website loads 24 listings at a time and then displays a "see more results" button to load the next batch of 24 listings while keeping the initial 24 visib ...

The component's width appears to be constrained by the use of display flex

I am currently working on a reactjs application that includes a header and another component. Initially, everything looks fine, but when I apply display: flex to their div, it seems to reduce the width of the header. Here are some images showing the issue: ...

Problem arising from apostrophe usage in Javascript OData request

In my current project, I have a text input field that passes a value through JS to fetch filtered data of names from a JSON file using OData query parameters. However, I've encountered an issue where if a name contains an apostrophe, it results in a ...

The animated image gracefully glides down the webpage accompanied by an h3

How can I align an image and h3 tag side by side without the image sliding down? <img src="..." alt="..." /><h3>Shopping Cart</h3> I need them to be next to each other but the image keeps moving down. Any suggestions on how to fix this? ...

Can the appearance of jqgrid be personalized to suit individual preferences?

I am looking to style my jqgrid to resemble the appearance of bootstrap tables. Is there a way to customize the visual design to achieve this? While I am aware that jqgrid supports jQuery themes, I specifically desire the bootstrap look and feel rather t ...

What is the best way to postpone one of the 3 ajax requests?

Can anyone assist me with handling AJAX forms? I am trying to ensure that the smallest one is executed after the others, but I also want to introduce a delay in the process. I attempted to utilize setTimeout(), however, it does not seem to be functioning ...

"Trouble with Ajax success handler - it's not functioning properly

$.ajax({ type: 'GET', url: 'https://example.com/api/v1/data?access_token=[TOKEN]', cache: false, dataType: "jsonp", crossDomain: true, jsonp: false, success: function(response){ alert("Data retrieved ...

query the database to retrieve information from a dropdown menu that shows connected services using the CodeIgniter framework

I am currently utilizing both Codeigniter and bootstrap in my project. Within my project, I have two select options named "service" and "sub-service". The values for these options are stored within an array. Here is a visual representation of the options: ...

Tips for creating a full-screen first page while keeping the others standard

Looking to create a dynamic HTML5/CSS/JS Website where the first page always displays in fullscreen mode with a background image, while the subsequent pages appear in a normal layout. Here's an example of what I'm aiming for: I've created ...

Eliminating redundant files in the upload section

Currently, I am using lodash clonedeep for the purpose of uploading files. I managed to write a function that prevents users from uploading identical files. However, I have encountered an issue where if I delete a file after uploading it, it remains in th ...

Tips for extracting text from a specific div using jQuery

Hey there, thanks for taking the time to read this message. I have some HTML code below: <div id="ImagePagination" class="Pagination"> Photo <span id="currentPhotoCount"><#currentPhotoCount#> </span> of <span i ...

displaying an image that has been uploaded inside a div element

Is it possible to display the uploaded image within a red box? Here is the code snippet: http://codepen.io/anon/pen/ZWXmpd <div class="upload-image"> <div class="upload-image-preview"></div> <input type="file" name="file" val ...

How can you display an HTML page retrieved through an API request in various ways?

After making an API call, I receive a single HTML page as a response. How can I display this on the frontend in the best possible way? I have successfully used HttpClient request to retrieve the data and utilized an iframe to display it, however, I now ai ...

Add up the duplicate elements in two arrays

I have dynamically created two arrays with the same number of cells (where array.length is the same, representing a key and value association). Below are the arrays: barData.labels["Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "Food", "F ...

What is the most efficient way to select all checkboxes with jQuery?

I'm not proficient in jQuery, but I attempted to create a script for my application to check all checkboxes, with no success. I first tried using the attr method, and then attempted the prop method, but it seems I'm missing something. Here is my ...