Running JavaScript function before page load (sett

2019-03-16 08:39发布

问题:

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?

回答1:

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.



回答2:

Check this article on getting screen resolution in Javascript: http://andylangton.co.uk/articles/javascript/browser-screen-resolution/

Script tags execute inline if you don't do anything special to defer them (and deferring script execution is not supported on all browsers). This means a script tag nested just inside the body tag will be executed before the rest of the body loads. You could have your script detect the screen resolution and set the background image for the body right there.



回答3:

Using a JavaScript framework like MooTools you can utilize the DomReady event instead of onLoad (which waits for all image elements to load) you can fire an event when the page has loaded.

Alternatively with CSS you can position absolute top left and width:100% to win the day. :O



回答4:

I realize you're specifically asking about JavaScript, but there's a pretty decent technique for doing this with CSS (and optionally a little JavaScript) described at the CSS Tricks site.