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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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.
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
See this example with some Gangsta Lipsum text.
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
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.