简体   繁体   English

包括我页面中的javascript文件

[英]including javascript files in my page

I have many (almost 15) javascript files which I am using in my webpage. 我有很多(差不多15个)javascript文件,我在我的网页中使用。 What is the best way to include all of these files? 包含所有这些文件的最佳方法是什么?

Simply at bottom or is there some other technique that should be used which can load javascript faster? 只是在底部或是否有一些其他技术应该可以加载javascript更快?

You could combine and minify them. 你可以结合并缩小它们。 YUI Compressor could do that. YUI Compressor可以做到这一点。

You may consider using a parallel/non-blocking javascript loader. 您可以考虑使用并行/非阻塞 javascript加载器。

Following are some great libraries that could do this for you.. 以下是一些伟大的图书馆,可以为你做这个..

http://headjs.com/ http://headjs.com/

http://requirejs.org/ http://requirejs.org/

http://labjs.com/ http://labjs.com/

Google Closure Compiler has a convient web api for merging and minifying all your js. Google Closure Compiler有一个方便的web api,用于合并和缩小所有js。 https://developers.google.com/closure/compiler/docs/api-ref https://developers.google.com/closure/compiler/docs/api-ref

You can put a script tag with a direct link to the api. 您可以将带有直接链接的脚本标记添加到api。

I haven't quite mastered implementing all this yet I have found that a fair amount of minification & concatenation can be automated by servers, I have learned a fair amount from reading the (well-commented) .htaccess file in the HTML5 Boilerplate and associated docs. 我还没有完全掌握所有这些,但我发现服务器可以自动完成相当多的缩小和连接,我通过阅读HTML5 Boilerplate中的(评论很好的).htaccess文件和相关联来学到了相当多的东西。文档。

Modernizr also features an asyncronous loader function and it was well enough documented that I was able to get it to work when I just couldn't quite figure out require.js Modernizr还具有异步加载器功能,并且有足够的记录,当我无法弄清楚require.js时,我能够使它工作。

You could use a script loader library or you can do it yourself. 您可以使用脚本加载器库,也可以自己完成。

Where to include scripts and how the browser loads resources 包含脚本的位置以及浏览器如何加载资源

Always at the bottom just before the closing <body> tag, to enhance the user experience. 始终在关闭<body>标签之前的底部,以增强用户体验。 It ensures that the page content gets rendered first, which gives the impression that your pages load quicker. 它可确保首先呈现页面内容,从而给您的页面加载速度更快。

The browser runs a single thread and will process the page content from top to bottom, if it happens on a resource, it first has to retrieve the resource, process it and then only continue with the next tag on the page. 浏览器运行单个线程并将从上到下处理页面内容,如果它在资源上发生,它首先必须检索资源,处理它然后只继续页面上的下一个标记。 Since we generally want to wait for the DOM to be finished loading, before running any scripts in any case, this strategy is always a win win. 由于我们通常希望等待DOM完成加载,因此在任何情况下运行任何脚本之前,此策略始终是双赢。

Size matters 大小事项

For production you want to ensure that all your scripts are minified regardless of the strategy you are going to employ to get them loaded (smaller size == less to download == quicker) 对于生产,您希望确保所有脚本都缩小,无论您将采用何种策略来加载它们(较小的尺寸==较少下载==更快)

The correct order 正确的订单

Most important is always the dependency order, if we call a function or access a variable and the browser doesn't know about it first, the script will fail. 最重要的是依赖顺序,如果我们调用函数或访问变量并且浏览器首先不知道它,脚本将失败。 You want to ensure that a script is only included after any scripts they depend on. 您希望确保脚本仅包含在它们所依赖的任何脚本之后。 So the first thing to do is to work out the order by which you need to include and introduce functionality to the browser. 因此,首先要做的是确定您需要在浏览器中包含和引入功能的顺序。

How to include scripts into a page 如何将脚本包含到页面中

There is only one way to include a script in a page (not recommending same origin ajax/eval) and that is by means of the <script> tag. 只有一种方法可以在页面中包含脚本(不推荐相同的原点ajax / eval),这是通过<script>标记。

There are only 2 ways to create a <script> tag: 创建<script>标记只有两种方法:

  1. Statically located in html or 静态地位于HTML或
  2. dynamically added with JavaScript. 动态添加JavaScript。

Statically added scripts 静态添加脚本

Since we know the order we need our scripts included we can add them one by one after each other like this 既然我们知道我们需要包含脚本的顺序,我们可以像这样一个接一个地添加它们

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.widgets.min.js"></script>

Dynamically added scripts 动态添加脚本

There are three ways to effectively create script tags in the dom, dynamically, which we will explore. 有三种方法可以动态地在dom中有效地创建脚本标记,我们将探索这些标记。 These are certainly not the only ways... 这些肯定不是唯一的方法......

document.write 文件撰写

The write method will append to the existing dom. write方法将附加到现有的dom。

document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>');

But now we have a problem as there is no way of telling that the script is done loading, because we have to wait until it is complete before loading the next one or calling something that is defined there. 但是现在我们遇到了一个问题,因为没有办法告诉脚本已经完成加载,因为我们必须等到它完成才能加载下一个或调用那里定义的东西。

document.createElement 使用document.createElement

The createElement method creates a dom element and we can insert it anywhere in the dom we choose. createElement方法创建一个dom元素,我们可以将它插入我们选择的dom中的任何位置。 The following example checks if jQuery exists or creates a <script> element to go fetch it. 以下示例检查jQuery是否存在或创建<script>元素以获取它。 In any event, the function ready_go is called and we should have jQuery. 无论如何,函数ready_go被调用,我们应该有jQuery。

(function() {
    if (!window.jQuery) {
        var jq = document.createElement('script');
        jq.type = 'text/javascript';
        jq.async = true;
        jq.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(jq, s);

        jq.onreadystatechange = jq.onload = ready_go;
    } else ready_go();
})();

jQuery.getScript jQuery.getScript

Since we have jQuery now we don't have to do things the hard way, getScript takes as first argument the script url and will call the function as 2nd argument once the script is complete. 由于我们现在有jQuery,所以我们不必采取艰难的方式,getScript将脚本url作为第一个参数,并在脚本完成后将该函数作为第二个参数调用。

function ready_go() {
    $.getScript('http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.min.js', function () {
         // script is done loading we can include the next
         $.getScript('http://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.5.2/jquery.tablesorter.widgets.min.js', function () {
             // script is done loading we can include the next or start using our stuff
         });
    });
}

Where to get the scripts from? 从哪里获取脚本?

You either want to get the scripts from public CDN or host them yourself. 您要么从公共CDN获取脚本,要么自己托管它们。 An important concept to bear in mind is that scripts, as with any other resources get cached by the browser and you will not be required to repeatedly download the same scripts. 需要记住的一个重要概念是,脚本与浏览器缓存的任何其他资源一样,您不需要重复下载相同的脚本。

Scripts from a Content Delivery Network 来自内容交付网络的脚本

The advantage of a CDN is twofold; CDN的优势是双重的;

  1. you get closer to the user, because a CDN consists of POPs distributed across the world and even though you are calling one url the server responding may be different 你越接近用户,因为CDN包含分布在世界各地的POP,即使你正在调用一个URL,服务器响应可能会有所不同
  2. many sites may use the same CDN if your user already got jQuery from google's CDN when visiting my site his browser will simply use the cache copy already in its possession when requested by you. 如果您的用户在访问我的网站时已经从谷歌的CDN获得了jQuery,那么许多网站可能会使用相同的CDN,他的浏览器只会根据您的要求使用其拥有的缓存副本。

Scripts served from origin (your server) 从源(您的服务器)提供的脚本

I agree with the strategy that @Mario and @Xharze suggests, beats including 18 scripts on every page. 我同意@Mario和@Xharze所建议的策略,每页都有18个脚本。

Use CDNs where scripts are available but for the rest. 使用可用脚本的CDN,但其余部分。

Concatenate all your scripts together, keeping in mind that the same dependency order applies, and minify them. 将所有脚本连接在一起,记住应用相同的依赖顺序,并将它们缩小。

Having one script will simplify your includes and because the browser will cache the script no additional downloads will be required again, especially beneficial in application used for extended periods and accessing many pages. 拥有一个脚本将简化您的包含,并且因为浏览器将缓存脚本,所以不再需要额外的下载,特别是在长时间使用的应用程序和访问许多页面时非常有用。

The only advantage separate scripts hold is for users who exit from the landing page and why do we care to optimise for them they're not going to stay because of it. 单独脚本保留的唯一优势是退出登录页面的用户以及我们为什么要为他们进行优化,因为它们不会留下来。

nJoy! 的nJoy!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM