简体   繁体   中英

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.

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

[...] having to first load libraries such as JQuery first.

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.

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.

For example, HeadJS is a 1.9KB library and it can solve your issue:

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.

Then using JavaScript you can use the document readyState to hide the preloader once everything is downloaded:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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