I am have that problem, that I got some javascript that shows a flexibg image. It only works if it on the bottom of the p开发者_运维问答age. just before
The problem is that the javascript gets loaded as the last. And I can see the flexi bg image just streching wish is not nice.
My code:
<%= javascript_include_tag 'flexibg.js' %>
</body>
What can I do so that the flexi bg javascript get loaded as the first or faster?
EDIT:
I have moved the javascript at the top of my body tag and it still works. But it is slow as hell.
Ok, to understand your problem you need a basic understanding of how a page loads. The short (not 100% accurate, but good enough) explanation is that the browser goes line by line, starting with the top line of the page. As it hits each script tag, it loads it (and does NOT move on to the rest of the lines until it is done, which is why it is considered best practice to put your script tags at the bottom).
As soon as the browser has (in its opinion) enough to be worth rendering, it starts rendering what it has. Very likely this is what is causing your problem: the browser is initially loading the image, with the wrong dimensions, and only when the JS gets loaded/run do the correct dimensions get set.
To solve this problem, what you have to do is hide the entire page initially, and then show it once the page has been loaded. Basically you want to do something to the effect of:
<script src="yourFile.js"/> <!-- This could go at the end -->
<body id="theBody" style="display:none"> <!-- rest of document --></body>
<script>document.getElementById("theBody").style.display = "";</script>
This way, the browser will hit the BODY tag, and subsequent content, but it won't render any of it because of the display:none style. Then, when the browser gets down to the end, it will hit the script tag that removes the display:none style, showing the page.
That's just a quick example, and some details might be off (I don't think script tags are allowed after the body tag, for instance), but hopefully you get the idea. If not, comment and I'll try to explain further.
精彩评论