What strategies can be implemented to avoid the delay in loading background content on a website?

Currently, I am working on a website built in aspx.net using the Microsoft Web Developer 2010 Express application. My goal is to create a dynamic background that changes as users scroll down the page and reverts back to the previous image when scrolling up.

To achieve this, I have written a JavaScript code that increments a global variable upon scrolling, determining which image should be displayed as the background. While the code works, I am facing an issue where the initial loading of the page causes a delay in displaying the background image when scrolling for the first time.

This problem can be observed in this video demonstration.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<link href="../css/css.css" rel="stylesheet" type="text/css" />
<script src="../JS/backgroundMovement.js" type="text/javascript"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        #form1
            height:10000px;
    </style>
</head>
<body onscroll="myFunction()">

    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>


var x = 1;
function myFunction() {
  // Function for changing the background while scrolling
  x += 1;
  switch (x % 20) {
    case 4:
      document.body.style.backgroundImage =
        "url('../pics/background1.png')";
      Break;
    case 8:
      document.body.style.backgroundImage =
        "url('../pics/background2.png')";
      Break;
    case 12:
      document.body.style.backgroundImage =
        "url('../pics/background3.png')";
      Break;
    case 16:
      document.body.style.backgroundImage =
        "url('../pics/background4.png')";
      Break;
    case 20:
      document.body.style.backgroundImage =
        "url('../pics/background4.png')";
      Break;
  }
}

The issue arises from images loading only when a user scrolls, causing a momentary white background before the image fully loads. To address this, I want all the images in my JavaScript code to load when the page initializes rather than wait until the page is scrolled. Is there a solution available for this?

Answer №1

To achieve the desired effect, opt for using CSS exclusively instead of relying on JavaScript. Incorporate images as background-images in consecutive divs and apply the background-attachment: fixed; property to each one. Simply adjust the width and heights accordingly.

This technique is commonly known as Parallax Scrolling, which you can explore further by searching online for various examples.

For instance, refer to this demonstration on W3Schools for a visual representation: Link

Answer №2

Instead of using the url(<address>) style for images, consider employing base64 encoding to embed image data directly into your CSS. This approach may slow down page load time, but it ensures that all images are readily available on the client side.

For example:

document.body.style.backgroundImage = "url(data:image/png;base64,<imagedatahere>)";

You can check out these resources for more information:

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

Change CSS style sheets depending on the size of the viewport

I've tried to implement the method from CSS-Tricks that allows for changing stylesheets based on the viewport width using multiple .css files and jQuery. However, my code isn't functioning as expected. I've spent the past hour trying to figu ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...

Node.js client-side code

Hi all, I am currently exploring Nodejs and experimenting with setting up a server-client connection using sockets. The server side seems to be functioning properly, but I am encountering some difficulties with the client side connection. I would appreciat ...

Ensure that both columns are of equal height

I attempted to create two columns with the same height, but it did not work as expected. Here is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title</title> < ...

How to Align Buttons Perfectly in Material-UI and React

I managed to center the button with the text "Hello There", but I'm having an issue where some lines are visible on the button. I could easily fix this by adding a white background-color, but I'm wondering if there is a more optimal way to achiev ...

jQuery-powered web application, experiencing compatibility issues when deployed on Windows Server 2003 and Internet Explorer

While developing a web application on XP and FF (with occasional IE checks through IE 8), I encountered an issue when deploying it to a WS 2003 site running IE 7. My jQuery code for dynamically sizing divs does not execute, even when explicitly stating div ...

How to efficiently target and manipulate links using jQuery Mobile

I previously asked a question about loading an external page without ajax while maintaining it as an iOS web app window. In that example, I used the following code: <script> $(document).bind('pageinit', function() { $("#test").click(func ...

Vue JS - Toggle visibility of an element based on radio button selection

When selecting between true or false radio buttons, I want a block to appear when "One" is clicked and be hidden when "No" is clicked. Here is the code snippet I used: <template> <div> <div> <label >One & ...

Activate a button only when a value is inputted into a text box associated with a chosen radio button

I'm facing a challenge with my radio buttons and sub-options. When a user selects an option, the corresponding sub-options should be displayed. Additionally, I want to enable the next button only when text is entered in all sub-option text boxes for t ...

Automated web browser capture downloading feature

Currently, I am in the process of developing a tool to streamline tasks at my workplace. One feature we need is an aspx webpage where users can input information, then click on a submit button. When the submit button is clicked, a javascript download dialo ...

Trouble with IFormCollection not retrieving individual form data

I've been working on an asp.net core MVC project where I encountered a requirement to add dynamic fields to a view that already has a form with static fields. These dynamic fields are fetched from the database and need to be submitted along with the s ...

Is there a way to transfer a JSON object to Excel using Nextjs/React?

How can I create a button that exports data from a JSON object to multiple file formats, including Excel (.xlsx)? "data": [ { "id": 1, "temaIndicador": "Indian", "codigo": "001", "observacion ...

Retrieving xml data using ajax

Hey there, I'm working with an HTML file that looks like this: <!DOCTYPE html> <html> <style> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 5px; } </style> & ...

modifying the appearance of the play button through a JavaScript event without directly altering it

I am currently working on building a music player from scratch using HTML, CSS, and JavaScript only. To store the list of songs, I have created an array named "songs" with details such as song name, file path, and cover image path. let songs = [ {songNa ...

The second instance of a React Paginate on the same page remains static and does not trigger a

Having a bit of trouble with using react-paginate for pagination - I have two instances on the same page (one at the top and one at the bottom). When a new prop is received, only the top instance gets re-rendered. The code seems to be working fine as all ...

Implement a javascript click action to alternate the visibility of an HTML element

Hey there! I'm a newcomer to Javascript and I'm currently working on a click function that will show an input element when a button is clicked, and hide it when the same button is clicked again. I've checked my console for error messages but ...

Troubleshooting PhantomJS hanging with WebdriverJS tests on Windows

I am currently using webdriverjs to run automated tests on a Windows 8 system. The tests run successfully when the browser is set to Chrome, but encounter issues when I switch to PhantomJS. Interestingly, the same tests run smoothly on OS X Mavericks. Ins ...

How to use Bootstrap to center an SVG or div in the middle of the page

I've been struggling to center this box for a week now, but no matter what I try, it keeps ending up on the center left. I attempted to use CSS to position it absolutely, but that ended up messing with the responsive design. Here is my HTML: <body ...

Various text sizes within a nested HTML list structure

I've developed a nested CSS class for an ordered list on my website, but I'm encountering a problem where each list item is appearing in different font sizes even though I have specified the font size. .number_list ol { font:normal 1.2em ...

"Create a new row in the list by selecting an option from the drop-down

I'm experimenting with the following scenario. There is a function that reveals a hidden list based on a dropdown selection. To see it in action, please click here. What I am aiming to achieve is for Option1 to display the content of #List-Option1 ...