简体   繁体   English

我将所有内容保存在一个外部.js文件中。 但并非所有功能都在每个页面上使用。 这会影响速度吗?

[英]I keep everything in an external .js file. But not all functions are used on every page. Does this affect speed?

My app's JavaScript/jQuery is contained in an external scripts.js file. 我的应用程序的JavaScript / jQuery包含在一个外部scripts.js文件中。 It generally looks like this: 通常看起来像这样:

$('document').on('ready', function() {
    giraffe();
    elephant();
    zebra();
});

function giraffe() {
    // code
}

function elephant() {
    // code
}

function zebra() {
    // code
}

giraffe() is only used for the view available at /animal/giraffe giraffe()仅用于/animal/giraffe可用的视图
elephant() is only used for the view available at /animal/elephant elephant()仅用于/animal/elephant可用的视图
zebra() is only used for the view available at /animal/zebra , zebra()仅用于/animal/zebra的视图,

But all 3 are supposed to run on the view available /animal/all . 但是所有这3个都应该在可用的/animal/all视图上运行。 This is a rudimentary example, but this is the reasoning behind having them all in one .js file, apart from keeping HTTP requests to a minimum. 这是一个简单的示例,但这是将它们全部保存在一个.js文件中的原因,除了将HTTP请求保持在最低限度之外。

My question is, does this affect the JavaScript rendering? 我的问题是,这会影响JavaScript渲染吗? Even though giraffe() isn't used (has no elements to work on) on /animal/zebra , it's still being called. 即使未在/animal/zebra上使用giraffe() (没有要处理的元素),仍在调用它。 Does js/jQuery ignore the function if it finds nothing to do? 如果JS / jQuery没有任何作用,它会忽略该函数吗? I'm sure the whole script is read, and that probably takes time. 我确定已读取整个脚本,这可能需要时间。 So, what's best way to handle this? 那么,处理此问题的最佳方法是什么?

One solution 一种解决方案

To avoid conflicts, I've created conditionals at the top of the js file to only run the functions that the active page needs: 为了避免冲突,我在js文件的顶部创建了条件语句,以仅运行活动页面所需的功能:

$('document').on('ready', function() {
    var body = $('body');

    if( body.hasClass('giraffe') ) {
        giraffe();
    }

    if( body.hasClass('elephant') ) {
        elephant();
    }

    if( body.hasClass('zebra') ) {
        zebra();
    }
});

This is a little more verbose than I would like, but it is successful in keeping these functions modular/conflict free. 这比我想要的更为冗长,但是可以成功地使这些功能保持模块化/无冲突。 I welcome an improvement on this solution. 我欢迎对此解决方案进行改进。

It would certainly be better to run just the code you need. 当然,只运行所需的代码会更好。 It's not that difficult; 这并不困难; the only minor complexity is handling your /animals/all case. 唯一的次要复杂性是处理/animals/all情况。 If you want to keep all your code in one file, you could do it this way: 如果要将所有代码保存在一个文件中,可以采用以下方式:

var animals = {
    giraffe: function() {
        console.log( "I'm a giraffe" );
    },
    elephant: function() {
        console.log( "I'm an elephant" );
    },
    zebra: function() {
        console.log( "I'm a zebra" );
    }
};

$(function() {
    var animal = location.pathname.split('/').pop();
    if( animal == 'all' ) {
        for( var animal in animals ) {
            animals[animal]();
        }
    }
    else if( animal in animals ) {
        animals[animal]();
    }
    else {
        console.log( "I'm a mystery animal" );
    }
});

You can actually test this code by going to URLs like this right here on Stack Overflow, and then pasting that code into the JavaScript console: 您实际上可以通过在Stack Overflow上转到如下所示的URL来测试该代码,然后将该代码粘贴到JavaScript控制台中:

https://stackoverflow.com/animal/giraffe https://stackoverflow.com/animal/giraffe
https://stackoverflow.com/animal/elephant https://stackoverflow.com/animal/elephant
https://stackoverflow.com/animal/zebra https://stackoverflow.com/animal/zebra
https://stackoverflow.com/animal/ocelot https://stackoverflow.com/animal/ocelot
https://stackoverflow.com/animal/all https://stackoverflow.com/animal/all

Update: OK, so you explained in the comment that the actual situation is a bit more complicated. 更新:好的,因此您在评论中解释了实际情况要复杂一些。 I'll leave this code here in case it's useful for anyone, but for your situation you may be closer to what you need with the code you already have. 如果对任何人都有用,我将在此处保留此代码,但是对于您的情况,您可能更接近于已经拥有的代码所需要的内容。

WRT the question of what one of your animal functions will do when you're on a page it doesn't relate to, of course that depends on how it's coded. WRT的问题是,当您在与页面无关的页面上使用哪种动物功能时,当然取决于它的编码方式。 It may successfully do nothing, or it may have an error, right? 它可能无法成功执行任何操作,或者可能有错误,对吧?

Since we're talking about jQuery code, here are a couple of examples. 由于我们在谈论jQuery代码,因此这里有两个示例。 Suppose you have code that's looking for an element by ID and then assumes that the element exists: 假设您有按ID查找元素的代码,然后假定该元素存在:

var zebraElement = $('#zebra')[0];
console.log( zebraElement.value );

On a page where the #zebra element exists, this code will log its value attribute. #zebra元素存在的页面上,此代码将记录其value属性。 (I'm assuming for discussion that it's an element that has a value, such as an input element.) (我为讨论起见,它是一个具有值的元素,例如输入元素。)

But if #zebra is not present, then zebraElement is undefined , and attemping to access its value will fail and land in the debugger. 但是,如果#zebra不存在,那么zebraElementundefined ,并且attemping访问其value在调试器将失败和土地。

OTOH, if you coded that like this: OTOH,如果您这样编码:

var $zebra = $('#zebra');
console.log( $zebra.val() );

it wouldn't fail if #zebra is missing, it would successfully print undefined without causing an error. 如果缺少#zebra ,它不会失败,它将成功打印undefined而不会引起错误。

Similarly, if you have code that uses $().each() , it will typically run without failure when the element(s) are missing, because it simply won't execute the callback function: 类似地,如果您有使用$().each() ,则当缺少元素时,它将通常不会失败地运行,因为它根本不会执行回调函数:

$('.animal').each( function( i, e ) {
    console.log( $(e).val() );
});

If there are no elements with class="animal" , then the console.log() call will never be reached. 如果没有元素带有class="animal" ,则将永远不会到达console.log()调用。 So there's no error, it just doesn't do anything. 因此没有错误,它什么也不做。

Depending on what you're doing, this can be a perfectly reasonable way to fire up only the behavior you need—simply make sure your code handles the missing DOM elements by cleanly doing nothing. 根据您的操作,这可能是一种完全合理的方法,它仅触发您需要的行为—只需确保您的代码通过不做任何事情即可处理丢失的DOM元素。

Also be sure to read nick's answer for more insights. 另外,请务必阅读nick的答案以获得更多见解。

And one more update… In the comment you mentioned keying off classnames on the body element. 还有一个更新…在注释中,您提到了在body元素上键入类名。 A nice way to do that would be similar to the code example above. 做到这一点的一种好方法类似于上面的代码示例。 You don't need a conditional for each animal, just a loop and a single conditional: 您不需要为每个动物设置条件,只需一个循环和一个条件即可:

var animals = {
    giraffe: function() {
        console.log( "I'm a giraffe" );
    },
    elephant: function() {
        console.log( "I'm an elephant" );
    },
    zebra: function() {
        console.log( "I'm a zebra" );
    }
};

$(function() {
    var $body = $('body');
    for( var animal in animals ) {
        if( $body.hasClass(animal) ) {
            animals[animal]();
        }
    }
});

So, for example, if you have <body class="giraffe zebra"> it will call the animals.giraffe() and animals.zebra() functions. 因此,例如,如果您具有<body class="giraffe zebra"> ,它将调用animals.giraffe()animals.zebra()函数。

There are actually two issues here, one is whether to load all the functions and the other is whether to run them all. 实际上,这里有两个问题,一个是是否加载所有功能,另一个是是否运行所有功能。 The question about whether to run them all (and some solutions to running just the functions you need) has been well addressed by Michael Geary in the other answers. Michael Geary在其他答案中已经很好地解决了有关是否全部运行它们(以及仅运行所需功能的一些解决方案)的问题。

So, should you load them all? 那么,您应该全部加载它们吗? You need to weigh up the time needed to download a larger file over making extra http requests. 您需要权衡下载更大文件所需的时间,而不是提出额外的http请求。 With only three 'groups' of functions shared between 3 pages (and one page using all of them) and when you expect the user to be changing pages regularly I would go with one file. 只有3个“组”的功能在3个页面之间共享(并且一个页面使用所有这些功能),并且当您希望用户定期更改页面时,我会使用一个文件。

Once your project gets very big you'll want to use something like requirejs to manage your scripts and load them asynchronously. 一旦项目变得很大,您将需要使用requirejs之类的工具来管理脚本并异步加载它们。 Loading your js scripts asynchronously will increase the speed of the page (and the perceived speed of the page) and if there are issues (especially with scripts hosted by third-parties) your page wont get help up. 异步加载js脚本会提高页面的速度(以及页面的感知速度),如果出现问题(尤其是第三方托管的脚本),您的页面将无法获得帮助。 You can of course do this without a library: 您当然可以在没有库的情况下执行此操作:

With HTML5: 使用HTML5:

<script async src="http://google.com/script.js"></script>

There are a million ways to load asynchronously with pure JS, one way: 有上百万种使用纯JS异步加载的方式,一种方式是:

<script>
  var resource = document.createElement('script'); 
  resource.src = "//google.com/script.js";
  var script = document.getElementsByTagName('script')[0];
  script.parentNode.insertBefore(resource, script);
</script>

Javascript will ignore any function that is not "called". Javascript将忽略任何未“调用”的函数。 Ie. 就是 if you do not call elephant() on any page other than the /elephant or /all page then it will never be used, nor give you any errors. 如果您没有在/ elephant或/ all页面以外的任何页面上都不调用Elephant(),则它将永远不会使用,也不会给您带来任何错误。

However, you may wish to not display functions on pages it is not being used for faster page loading. 但是,您可能不希望在不用于快速加载页面的页面上不显示功能。 Consider, separate JS files for certain pages, or by loading certain JS scripts from a back-end server such as PHP to determine which functions are needed. 考虑为某些页面分离JS文件,或者通过从诸如PHP之类的后端服务器加载某些JS脚本来确定需要哪些功能。

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

相关问题 addEventListener在外部Javascript文件中不起作用,但是在直接放在ASP页上时起作用。 为什么? - The addEventListener does not work in external Javascript file, but does when placed directly on ASP page. Why? 弹出窗口的数量是否会影响页面加载速度? - Does the number of popovers affect page load speed? 如何获取节点js模块中使用的所有外部函数 - How to get all external functions used in node js module 当我克隆文件输入时,克隆的输入不会保留上载的文件。 原始输入 - When I clone a file input, the cloned input does not keep the uploaded file. The original input does 页面未协调外部js文件 - page does not reconize external js file 如果我不重新加载页面,为什么我的 js 无法正常工作。 这是用于 CS50 Web 项目 3 - Why does my js work incorrectly if i do not reload the page. This is for CS50 Web Project 3 网页中使用的外部JS文件的控制到期 - Control expiry of an external JS file used in a web page 为所有内容添加一个外部js文件? - Add one external js file for everything? 附加外部js和CSS文件中的页面速度 - Page Speed in appending external js and css files 如何分配在所有js文件功能中使用的const? - how assign a const to be used in all js file functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM