开发者

How to Load Javascript Simultaneously with 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 cod开发者_如何学Goe which sets the elements width after the element was rendered in HTML.


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.com/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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜