简体   繁体   English

预加载JS,但不要运行它

[英]Preload JS, but don't run it

I want to preload a large JS file after a page has loaded, so that when I link to that JS file on the required page it is already downloaded and cached. 我想在页面加载后预加载一个大的JS文件,以便当我链接到所需页面上的该JS文件时,该文件已经下载并缓存了。

I'm basically doing this at the moment, and it works, but of course it's not the right way: 目前,我基本上正在这样做,并且可以正常工作,但是当然这不是正确的方法:

preload_js = new Image();
preload_js = "http://domain.com/files/file.js";

This seems such a quick and simple method, no Ajax needed etc. and it works great. 这似乎是一种快速简单的方法,不需要Ajax等,并且效果很好。

What's the proper way to do this? 正确的方法是什么? Surely not with Ajax as that seems overkill for this. 当然不能与Ajax一起使用,因为这似乎太过分了。

I know there's lots of methods for loading JS but they all seem to actually run the code after the script has loaded, which I don't want. 我知道有很多加载JS的方法,但是它们似乎都在脚本加载后实际运行了代码,这是我所不希望的。

I don't want to use jQuery (or any library), it must be plain JS. 我不想使用jQuery(或任何库),它必须是纯JS。 Thanks for any help. 谢谢你的帮助。

From this blog post : 这篇博客文章

Preloading components in advance is good for performance. 预先预加载组件有助于提高性能。 There are several ways to do it. 有几种方法可以做到这一点。 But even the cleanest solution (open up an iframe and go crazy there) comes at a price - the price of the iframe and the price of parsing and executing the preloaded CSS and JavaScript. 但是,即使最干净的解决方案(打开iframe并在那里疯狂)也要付出代价-iframe的价格以及解析和执行预加载的CSS和JavaScript的价格。 There's also a relatively high risk of potential JavaScript errors if the script you preload assumes it's loaded in a page different than the one that preloads. 如果您预加载的脚本假定它加载的页面与预加载的页面不同,则存在潜在JavaScript错误的风险也相对较高。

After a bit of trial and lot of error I think I came up with something that could work cross-browser: 经过一番尝试和许多错误之后,我认为我想出了一些可以跨浏览器使用的功能:

  • in IE use new Image().src to preload all component types 在IE中使用new Image().src预加载所有组件类型
  • in all other browsers use a dynamic <object> tag 在所有其他浏览器中,使用动态<object>标签

In this example I assume the page prefetches after onload some components that will be needed by the next page. 在本示例中,我假定页面在加载后会预取页面下一页所需的某些组件。 The components are a CSS, a JS and a PNG (sprite). 这些组件是CSS,JS和PNG(精灵)。

 window.onload = function () { var i = 0, max = 0, o = null, // list of stuff to preload preload = [ 'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.png', 'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.js', 'http://tools.w3clubs.com/pagr2/<?php echo $id; ?>.sleep.expires.css' ], isIE = navigator.appName.indexOf('Microsoft') === 0; for (i = 0, max = preload.length; i < max; i += 1) { if (isIE) { new Image().src = preload[i]; continue; } o = document.createElement('object'); o.data = preload[i]; // IE stuff, otherwise 0x0 is OK //o.width = 1; //o.height = 1; //o.style.visibility = "hidden"; //o.type = "text/plain"; // IE o.width = 0; o.height = 0; // only FF appends to the head // all others require body document.body.appendChild(o); } }; 

See the post for more details. 有关更多详细信息,请参见该帖子


EDIT: Looking at the comments on that post, someone mentions this link , which talks about the problems with the new Image() preload method in IE and other browsers. 编辑:查看该帖子的评论,有人提到此链接该链接讨论IE和其他浏览器中new Image()预加载方法的问题。 Here's an excerpt: 摘录如下:

When IE encounters an IMG tag, it creates an image object and assigns the download request to it. 当IE遇到IMG标签时,它会创建一个图像对象并为其分配下载请求。 As data arrives from the image download, it's fed into the browser's image decoders. 当数据从图像下载中到达时,数据被馈送到浏览器的图像解码器中。 The decoders will reject data as malformed if you feed them plaintext, which seems reasonable, since they can't possibly make use of such data. 如果您以纯文本格式提供数据,则解码器将拒绝格式错误的数据,这似乎是合理的,因为它们可能无法利用此类数据。 When the decoders reject the data as "Not possibly an image," the image object will abort its processing. 当解码器将数据拒绝为“不太可能是图像”时,图像对象将中止其处理。 As a part of that abort, if the download has not yet completed, it too is aborted. 作为中止的一部分,如果下载尚未完成,则它也将中止。

This explains the behavior mentioned by the OP in the comment below (IE9 only downloading 4KB of the file). 这解释了OP在下面的注释中提到的行为(IE9仅下载4KB的文件)。

It seems like your only reliable cross-browser option may be to use Ajax... 似乎唯一可靠的跨浏览器选项可能是使用Ajax。

USE 使用

window.document.onload =function(){
preload_js = "http://domain.com/files/file.js";
}

window.document.onload make sure the java script will not run until you dom is ready window.document.onload确保直到dom准备好Java脚本才会运行

Considering the cross domain issues with Ajax, especially since there really is no way to load a file on a server you have no control over (eg Google CDN hosting jQuery), this is my solution: 考虑到Ajax的跨域问题,尤其是由于实际上没有办法在您无法控制的服务器上加载文件(例如,托管jQuery的Google CDN),这是我的解决方案:

(1) Use the document.createElement('object') part in Simon M's solution for Firefox as that works great. (1)使用Simon M的Firefox解决方案中的document.createElement('object')部分,因为效果很好。

(2) Use the new Image.src thing for every other browser. (2)在其他所有浏览器中使用新的Image.src。 Opera, Safari and Chrome love it. Opera,Safari和Chrome浏览器都喜欢它。 Also, I mentioned earlier that Mobile Safari doesn't work. 另外,我之前提到移动Safari不起作用。 Well it does, but for some reason takes 100ms verifying something (it is properly cached and it isn't just returning a 304 not modified). 确实可以,但是出于某种原因需要花100毫秒来验证某些内容(已正确缓存,而不仅仅是返回未修改的304)。 I can live with 100ms. 我可以忍受100ms。

I've not tested other mobile browsers. 我尚未测试其他移动浏览器。

(3) Bollocks to IE as nothing works. (3)Bollocks对IE无效,

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

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