Reputation: 58301
Is there any technique to render a javascript file in the same time as the HTML is rendering?
My first idea was to load it into the head in a <script>
tag, but as I see this doesn't affects the loading order, or I am false?
The problem is that in some times I need to use javascript to set an element's width when the page loads, and it's really annoying the little vibration what is because the javascript code which sets the elements width after the element was rendered in HTML.
Upvotes: 2
Views: 3321
Reputation: 1434
Yes you can with a tiny loader javascript like JcorsLoader (only 647B with Gzip)
JcorsLoader.load(
"http://xxxx/jquery.min.js",
function() {
$("#demo").html("jQuery Loaded");
},
"http://xxxx/jquery.cookie.js",
function() {
$.cookie('not_existing');
}
);
Load multiples js in parallel and execute in order without blocking DOMReady or onload.
https://github.com/pablomoretti/jcors-loader
Upvotes: 1
Reputation: 6928
You could use document.write
in an inline script block to output the element's HTML, including an inline style
. It will be ugly though; are you sure you can't avoid the whole thing?
Edit: a cleaner method is to document.write
an inline style block that sets the element's width using an id selector before the element's HTML; this will degrade better but still avoids any potential problem of accessing the DOM before it's ready:
<script type="text/javascript">
var width = ...;
document.write('<style type="text/css">#myid{width:' + width + 'px;}</style>');
</script>
<div id="myid">...</div>
Upvotes: 0
Reputation: 385098
Make the element render in HTML as invisible, and have the Javascript set the width then make it visible.
Upvotes: 4
Reputation: 50009
Unless you set the async flag (in some browsers) the JS file will block the loading of the content. So you can run your JS script from the moment it has loaded.
Might be better if you looked at a CSS solution though.
Support for async tags : Which browsers support <script async="async" />?
Upvotes: 2