推迟JS加载-插入头部或身体 [英] Defer JS loading - insert to Head or Body

查看:161
本文介绍了推迟JS加载-插入头部或身体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在优化,缓存和页面加载速度方面最推荐的方法是什么.使用Defer加载时,是否应该在网站文档的BODY或HEAD中动态插入JS文件?

I wanted to know what is the most recommended way in terms of optimization, caching and page load speed. Should I dynamically insert the JS files in the BODY or HEAD of my website document when using Defer loading?

推荐答案

如果使用的是DEFER,则将脚本标记放在HEAD或BODY上与脚本运行或缓存的时间无关紧要.无论哪种方式,它都将在页面解析完成后运行,并根据随javascript文件发送的服务器标头进行缓存.

If you are using DEFER, it does not matter whether you put the script tag in the HEAD or BODY as far as when the script will run, or cache. Either way, it will run after the page is finished parsing, and will cache according to the server headers sent with the javascript file.

您可能仍希望将脚本标签放在正文的末尾,以针对较旧的浏览器忽略DEFER属性的情况进行优化.

You may still want to put the script tags at the end of the body to optimize for the case where an older browser ignores the DEFER attribute.

或者,您可能希望将Script标记放在HEAD中,以按获取顺序更早地获取javascript文件(例如,在主体中指定的图像,音频或视频文件之前).

Alternatively, you may want to put the script tags in the HEAD to get the javascript files earlier in the fetching order (before images, audio, or video files specified in the body, for example).

这篇关于推迟JS加载-插入头部或身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆