简体   繁体   English

如何在香草javascript中预加载大型CSS和javascript文件

[英]How to preload large css and javascript files in vanilla javascript

I'm building a single page application that's going to run on tablets in areas of the world that have slow connections with poor bandwidth. 我正在构建一个单页面应用程序,该应用程序将在世界上连接速度较慢且带宽较差的地区的平板电脑上运行。

Because the javascript files and css files are quite big, the css file is 250kb and the main js file is 750kb at the moment, I'm looking for a best practice to preload the css and javascript files without having to first load libraries such as JQuery first. 由于javascript文件和css文件很大,目前css文件为250kb,主要js文件为750kb,我正在寻找一种最佳方法来预加载css和javascript文件,而不必先加载诸如首先使用jQuery。

So in short: What is a good way to preload css and js files without 3rd party libraries and have some sort of callback once all the files are loaded 简而言之:在没有第3方库的情况下预加载css和js文件并在加载所有文件后进行某种回调的好方法是什么

[...] having to first load libraries such as JQuery first. 首先必须加载诸如JQuery之类的库。

What you want to achieve can be done without libraries or frameworks (actually they still use vanilla JS under the hoods), anyway, science moves on when everyone don't try to re-invent the wheel every day. 您可以在没有库或框架的情况下完成您想要的目标(实际上,他们仍然在使用引擎盖JS),无论如何,当每个人都没有每天尝试重新发明轮子时,科学就在前进。

There're simple but yet powerful libraries that have a very small footprint that are just there to asynchronously-loading JavaScript and CSS files that work like a charm. 有一些简单但功能强大的库,它们的占用空间非常小,可以异步加载像魅力一样工作的JavaScript和CSS文件。

For example, HeadJS is a 1.9KB library and it can solve your issue: 例如, HeadJS是一个1.9KB的库 ,它可以解决您的问题:

head.load("myfile1.js", "myfile2.js", "mystyles.css", function() {
   // Do stuff once they got loaded!
}); 

Create an inline html/css preloader which is shown by default. 创建一个默认显示的内联html / css预加载器。

Then using JavaScript you can use the document readyState to hide the preloader once everything is downloaded: 然后,使用JavaScript,可以在下载所有内容后使用文档readyState隐藏预加载器:

document.onreadystatechange = function () {

// check the value - if it's 'complete' then everything has loaded
if (document.readyState === "complete") {
    // add code here
    // alert('everything has downloaded!')
    // e.g. preloader.style.display = 'none';   
    }
}

This is the equivalent to the $(window).load() you would use in jQuery. 这等效于您将在jQuery中使用的$(window).load()

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

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