The loading time of Javascript is dragging on

The loading sequence for the javascript in the "intro" div is currently causing a delay. The background image loads first, followed by the javascript, resulting in a slow overall load time. Is there a way to display a "loading please wait" message within the "intro" div until it fully loads? Ideally, I want the intro section to load before anything else on the page.

Here is the Javascript code:


var tl = new Array(
    "=======================",
    " Welcome user, ",
    " ###########################################"
);
var speed = 50;
var index = 0;
text_pos = 0;
var str_length = tl[0].length;
var contents, row;

function type_text() {
    contents = '';
    row = Math.max(0, index - 20);
    while (row < index)
    contents += tl[row++] + '\r\n';
    document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
    if (text_pos++ == str_length) {
        text_pos = 0;
        index++;
        if (index != tl.length) {
            str_length = tl[index].length;
            setTimeout("type_text()", 500);
        }
    }
    else setTimeout("type_text()", speed);
}

This script types out text letter by letter in a text area within the "intro" div. However, the issue is that it only starts running after the entire page has finished loading. It waits around 15 seconds before beginning to print the text.

Answer №1

One can listen to the "domready" events on the document, although this method may not work consistently across all browsers as documented here.

For example, in Mozilla:

   document.addEventListener("DOMContentLoaded", methodName, false)

A more reliable alternative is using jQuery's .ready() event handler, which ensures cross-browser compatibility.

For example:

$(document).ready(function(){
   //execute code here
});

//Shorthand
$(function(){
 //...
});

For further insights into domready, refer to this related question.

Answer №2

Begin by loading a page containing the intro div which is empty, initiate the script displaying "loading please wait," afterwards send an ajax request to fetch the remaining content of the page and subsequently refresh the page upon completion of the ajax request.

Answer №3

Utilizing jQuery for Page Load

   $(document).ready(function() {
      // implement changes to div content here 
    });

Check out the jQuery documentation on ready event

Alternatively, you can achieve the same with

window.onload = (function() {
  // update content in div element        
};

Answer №4

To achieve this effect, utilize jquery by enclosing the content in a div tag and then another div that displays a loading image. Here is an example:

$(document).ready(function () {
    $('#loading').show();

    $('#divShowMeLater').load(function () {
        $('#loading').hide();
        $('#divShowMeLater').show();
    });
})

In this scenario, consider divShowMeLater as the div containing all loaded content. The code structure would resemble the following markup:

<div id="divShowMeLater" style="margin-left:auto;margin-right:auto;text-align:center;" >
    <div id="loading">Page loading...
        <img src="images/ajax-loader.gif" alt="loading page..." />
    </div>
</div>   

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 - combining properties using "concatenation"

I'm currently pulling data from JSON for a three.js scene. My goal now is to transform data such as "position.x : 1" into object[ position ] [ x ] = 1. The syntax object [ key ] = value isn't effective in this case. This would result in object[ ...

Unable to employ the executescript method in Selenium with multiple arguments

I am currently working on automating a website to create a list through input values in a text field and setting them by clicking outside the field. Due to slow performance with Internet Explorer, I am using Selenium webdriver with IE. The sendKeys method ...

Adjusting the Absolute Position of CSS Elements on Mobile Devices (Equal Screen Size)

I always seem to run into problems with absolute positioning in CSS. It's frustrating because it looks fine on Chrome and Firefox, even when I test responsiveness by adjusting the browser window size. However, on mobile devices with the same screen si ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...

Completely adhering to standards and employing a semantic method for creating sections that utilize the

My goal is to create sections with a minimum height of 100%, and it seems like the general recommendation is: html{ height: 100%; } body { min-height: 100%; } Even direct children should have a min-height of 100%. The confusion arises when HTML has a ...

Tips for continuously randomizing colors in p5.js

I recently began exploring p5.js and I have a query regarding color randomization. Currently, it seems that the color only changes randomly when I restart the code. Is there a way to trigger this randomization every time the mouse is clicked? Below is the ...

Achieving click detection on a link within an iframe in Angular 2

Is there a way to detect a click on a link within an iframe? <iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe> Inside my iframe component, I have a simple code that listens to changes in observable var ...

Visualization of geometrical shapes in Three.js using Json formatting

I am seeking help with displaying the wireframe of a parallelepiped defined by vertexes in Json format using Three.js code. Here is the code snippet I am working with: var testCube ={ "metadata":{ "version":json['versi ...

What is the best way to correctly showcase dynamic pages in ExpressJS?

Within my app.js file, there exists an array of objects that is defined as follows: var people = [ {name: "Henrique Melo", username: "heenrique", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a121f1408130b0f1 ...

What is the best way to modify a current state object without causing an endless loop of redirects?

const useCase = (argument) => { const [value, setValue] React.useState(argument) React.useEffect(() => setValue({...value ...argument), [argument, value, setValue]) } The above code is currently causing an infinite loop due to setting the stat ...

Having no choice but to resort to using the 'any' data type in a Typescript/Vue3 project

My function is composed to return an array of objects, while another function takes a string as input and does not return anything. The code below functions without any errors: import { ref } from "vue"; import { useRoute } from "vue-router ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

How to use puppeteer to extract images from HTML that have alt attributes

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1">&l ...

Unleashing the hidden power of a website's jQuery function - the ultimate guide!

I am looking to modify the delayedAutoNext function found on the homepage of pitchfork.com which rotates the pitchfork.tv images. My goal is to adjust the setTimeout value to a new number. Is there a way to accomplish this using a bookmarklet or userscrip ...

Trouble arises when attempting to bind a JavaScript event with an innerHTML DOM element

I am currently dealing with a complex issue on how to bind a JavaScript event to an innerHTML DOM element. The scenario involves having a div with an input checkbox inside it, along with some pre-existing JavaScript event bound to that checkbox. Additional ...

Javascript not waiting for function return when using console.log statement

I am facing an issue where I need to set a variable x to the result obtained from the showData function. Below is my code snippet: app.post("/view/show", (req,res) => { let x = showData(req.body.custmerName); console.log(x); } Here&ap ...

Please input new items by clicking a button

I have a dilemma with handling an array of objects in my Vue component. I am using v-for to display the objects, but now I want to update certain items in the array and save only those changes in a new object. Currently, when I attempt this by mapping over ...

Upload dojo.js to my server for use

Check out this link for a working example: It's functioning perfectly. I then copied the HTML and tried running it on my local Apache server. Surprisingly, it worked! However, when I attempted to load the same dojo.js file on my web server, it ...

Bootstrap Photo Loader

I am currently working on a project using a bootstrap image upload plugin. However, I have encountered an issue in my services edit page where I am unable to display auto thumbnails of previously uploaded images. When I click the upload button and select a ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...