开发者

Loading jQuery asyncronously

My google analytics is supposed to load asynchrono开发者_运维问答usly. I am not sure really what this means:

<script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'xxx']);
        _gaq.push(['_trackPageview']);

        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
    </script>

I don't need jQuery to be available immediately. Is there a way I can also make this asynchronous?


Google Analytics is loading asynchronously in your example. The part that handles that is ga.async = true;. Asynchronous means that the browser will continue to load rest of the content even if this one takes longer to load. In older browser, the content would be loaded in the order of the document and if something was slow to load, it would take longer for the browser to display the page.

If you want jQuery to load asynchronously, simply add async="async" to your <script> tag. Please keep in mind that only newer browser support this.

Alternatively, Google does offer Google Loader which allows you to load jQuery and many other libraries asynchronously. You can have a look at this Stack Overflow question for an example.


HeadJS provides a nice API for this sort of thing.

JavaScript loader Load scripts in parallel but execute in order

Head JS loads JavaScript files like images without blocking the page. Your page will be faster even with a single combined file.

head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js",
function() {
    // all done
});


I use this function to load JavaScript files asynchronously:

function loadJS(url) {
    var js = document.createElement('script');
    js.src = url;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(js);
}

Then just call it like this:

<script type="text/javascript">
    loadJS("http://pathToJSFile");
</script>   


On Onload () event of a page you can insert a function that will automatically assign references to the JavaScript files you want to load in asynchronous manner after page loading.

function afterLoad(){
  var element1 = document.createElement(“script”);
  element1.src = “somefile.js”;
  element1.type=”text/javascript”;
  element1.async=true;
  document.getElementsByTagName(“head”)[0].appendChild(element1);
}

For more info check out http://www.tutkiun.com/2010/07/load-javascript-after-pageload.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜