简体   繁体   中英

Pre-load external JavaScript library for later pages

I use an external JavaScript library that is hosted on a CDN.

Some users report that when they first visit the pages that require this library, it takes a little while to load as well as to render stuff (the library renders LaTeX).

I wonder if I can optimize their experience by (pre-)loading this library on some other pages before they arrive at the pages that actually use it. This way, I hope the browser will cache the library early, so the rendering may happen faster later.

PS the library in question is MathJax.

Since you're interested in MathJax specifically, simply loading it won't buy you that much performance. (Though MathJax will be cached and if you use the MathJax CDN your users might already have cached it while visiting some other site.)

There are two reasons for why you probably won't see much of a performance increase.

First, MathJax loads most of its components dynamically. For example, the MathJax webfonts will only be loaded if no compatible font is installed on a user's system and they are also broken up into several pieces, to be loaded only when MathJax actually encounters a character. The same goes for other components. This also means that on a page without any mathematics, loading MathJax will not help you cache much.

That being said, the actual download of MathJax components can be optimized a bit by using one of the combined configuration files ending on -full , see the MathJax documentation .

However, it's the typesetting that's usually the real performance hit. MathJax output depends on your content as well as the user's combination of screen, browser, and OS. Both calculating the best fit as well as inserting & reflowing the content is an issue that has some fundamental limits (IE8 does a particularly bad job in standards mode).

PS: If you have hidden or dynamic content, you might want to look at the configuration option skipStartupTypeset: true ; see the MathJax documentation .

[Disclaimer: I'm part of MathJax]

If you add a script tag calling the library at the end of your page (just before the html closing tag), everything else will load prior to it and the user can start using the page while the library is still loading.

EDIT: This allows you to "pre-load" the library on another page withtout slowing it down.

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