Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running JavaScript function before page load (setting background of appropriate size)

I've got an image background which content I want to be always visible, no matter what is the user's resolution. Therefore, I want to be able to determine what is the resolution and set appropriate background image file before page loads, on the very beginning. Is it possible somehow?

like image 679
kremuwa Avatar asked Oct 22 '10 20:10

kremuwa


People also ask

How do you run a function before the page is loaded in JavaScript?

The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.

How do you execute a function when a page is fully loaded?

Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.

How can I make the browser wait to display the page until it's fully loaded?

It's just enough to make sure the page doesn't display until it's fully loaded. In FireFox and other browsers, the solution I've used is to create a DIV that is the size of the page and white, then at the very end of the page put in JavaScript that hides it. Another way would be to use jQuery and hide it as well.

Which event do you use to run something after the page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


1 Answers

The earliest point at which you can run a Javascript function with access to the DOM (without waiting for page load) is by placing a <script> tag right after the opening <body> tag.

Scripts inside the <head> will run before this occurs, but there won't be access to the elements on the page.

Try this code

<body>
    <script type="text/javascript">
        alert("Some elements shouldn't even be visible when this shows");
    </script>
    ... rest of the page
</body>

See this example with some Gangsta Lipsum text.

like image 151
Marko Avatar answered Sep 19 '22 18:09

Marko