我在哪里可以将我的Javascript / jQuery文件的链接放到我的html文件中? [英] Where do I put the links to my Javascript/jQuery files in my html file?

查看:125
本文介绍了我在哪里可以将我的Javascript / jQuery文件的链接放到我的html文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我注意到,我的一些(不是全部)我的javascript和jQuery脚本不会工作,除非我把.js文件的链接放在页面底部而不是我放置链接的头部区域我的.css文件。



据我所知,javascript可以在任何地方使用,建议不要放在页眉中,因为它会减慢页面加载过程以及。同时,如果我把它放在html文件的body标签中,它看起来有些杂乱,并想知道将.js文件放在干净的地方的最佳做法是什么。我应该总是把它放在结束身体标记之前的最下方吗?专业的Web开发人员如何处理这个问题?解析方案

如果你的脚本不工作,除非你把它们放在底部,那么你最有可能在DOM尚未准备好时开始操作DOM(或者您使用过document.write,但我怀疑是这种情况)。为了解决这个问题,你只需要在DOM准备好的时候开始处理。用jQuery你需要这样的东西:

  $(function(){
// DOM在这里准备好了,你可以安全地操作它
});

关于脚本的定位如何影响性能,我建议您从客户端的guru中阅读这3篇文章一方表现:

>

异步加载延迟执行是目前非常热门的主题。它们允许您在< head> 中清晰地定义所有内容,但要详细说明它们如何加载以及何时执行。


I recently noticed that some (not all) of my javascript and jQuery scripts wouldn't work unless I put the link for the .js files nearer towards the bottom of the page instead of the head area where I put my links for my .css files.

From what I understand, javascript can go in either places and it is recommended to not be put in the header as it slows down the page loading process as well. At the same time, if I put it in the body tag of the html file, it looks somewhat messy and was wondering what the best practice is for putting .js files in a cleanly place. Should I always put it at the very bottom right before the ending body tag? How do professional web developers handle this?

解决方案

If your scripts did not work unless you put them towards the bottom then you most probably started manipulating the DOM when the DOM wasn't ready yet (or maybe you used document.write, but I doubt that this was the case). To solve this you need to start processing only when the DOM is ready. With jQuery you'll need something like:

$(function() {
    // DOM is ready here and you can safely manipulate it
});

Regarding how the positioning of the scripts affects performance I suggest you read those 3 articles from the guru of client side performance:

Asynchronous loading and delayed execution are very hot subjects right now. They allow you to cleanly define everything at the <head> but be very specific about how they get loaded and when they are excecuted.

这篇关于我在哪里可以将我的Javascript / jQuery文件的链接放到我的html文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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