[英]How do I execute JavaScript, page specifically, from one file?
I have a single file, 'core.js', with a collection of my sites JavaScript. 我只有一个文件“ core.js”,其中包含我的网站JavaScript的集合。 I like to combine my script this way so I can cut down on HTTP requests. 我喜欢以这种方式组合脚本,以便减少HTTP请求。 My problem is, page specific code's, obviously, getting run on pages it needn't. 我的问题是,页面特定的代码显然可以在不需要的页面上运行。
Without splitting 'core.js' into separate scripts, what's the best solution for ensuring my page specific code only gets run on the page it's supposed to be run on? 在不将“ core.js”拆分为单独的脚本的情况下,确保我的页面特定代码仅在应该运行的页面上运行的最佳解决方案是什么?
Many thanks! 非常感谢!
The simplest way is to make everything in core.js be functions and then put one inline function call in each given page to call the code specific to that page. 最简单的方法是使core.js中的所有内容成为函数,然后在每个给定页面中放置一个内联函数调用以调用特定于该页面的代码。 That makes core.js a resource and each page decides what functions in that resource to call. 这使core.js成为资源,每个页面决定该资源中要调用的函数。
I've also seen it done where you put a trigger class name on the body tag and then the code in core.js examines the classes on the body tag to decide what initialization code to run. 我还看到了将触发器类名放在body标签上,然后core.js中的代码检查body标签上的类以确定要运行的初始化代码的方法。 This works best when you have a small number of types of pages and you want to run the same initialization code on all pages of the same type, but I don't think it's all that good if each page has different JS. 当页面类型较少并且要在相同类型的所有页面上运行相同的初始化代码时,这种方法效果最好,但是如果每个页面具有不同的JS,我认为这并不是很好。 In that case, I think it's better to use the first technique of let the page decide what JS initialization function to call. 在这种情况下,我认为最好使用让页面决定要调用的JS初始化函数的第一种技术。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.