admin管理员组

文章数量:1392073

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.

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.

Share Improve this question asked Mar 21, 2011 at 12:28 Adam HalaszAdam Halasz 58.4k67 gold badges153 silver badges216 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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

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

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./pablomoretti/jcors-loader

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>

本文标签: How to Load Javascript Simultaneously with HTMLStack Overflow