Running JavaScript function before page load (sett

2019-03-16 08:37发布

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?

4条回答
三岁会撩人
2楼-- · 2019-03-16 08:53

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.

查看更多
劫难
3楼-- · 2019-03-16 08:59

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.

查看更多
你好瞎i
4楼-- · 2019-03-16 09:02

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

查看更多
Viruses.
5楼-- · 2019-03-16 09:10

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.

查看更多
登录 后发表回答