2

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.

4 Answers 4

4

Make the element render in HTML as invisible, and have the Javascript set the width then make it visible.

2

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" />?

0
1

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

1
  • Out of all the plugs I've tested, this one actually does what it is so-pose to do. yepnope and alike are crap - look, they haven't even worked on them for 2+ yrs. Sorry 4 the dig but I've wasted wks on testing these plugs.
    – user742030
    Commented Mar 1, 2014 at 12:39
0

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.