开发者

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?


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜