Preload script file

后端 未结 4 1864
深忆病人
深忆病人 2020-12-22 04:25

There are numerous plug-ins to preload images, but is there a way to preload javascript? My application uses a big js file and it take about 5 seconds or so to load before t

4条回答
  •  星月不相逢
    2020-12-22 04:41

    This is the current standard:

    
    ...
    

    or you can just append it

    var preloadLink = document.createElement("link");
    preloadLink.href = "script-to-preload.js";
    preloadLink.rel = "preload";
    preloadLink.as = "script";
    document.head.appendChild(preloadLink);
    

    then when you want to use it:

    
    

    or

    var preloadedScript = document.createElement("script");
    preloadedScript.src= "/js/script-to-preload.js";
    document.head.appendChild(preloadedScript);
    

    to check if your browser is compatible with it just use this snippet of code: https://gist.github.com/yoavweiss/8490dabb3e0aa112fc74

    in case it isn't supported you can use the deprecated prefetch instead of preload

    source:

    https://w3c.github.io/preload/#x2.link-type-preload

    https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

    https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/supports

提交回复
热议问题