Preload script file

后端 未结 4 1865
深忆病人
深忆病人 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:27

    Step 1: Set the type attribute of your script tag to something invalid, such as "invalid", or your favorite swear-word.

    
    

    Step 2: At some later point, when the script has been loaded (such as, after window.onload event has occurred), just do this:

    var myScript = document.getElementById('myScript');
    document.head.removeChild(myScript);
    myScript.setAttribute('type', 'text/javascript');
    document.head.appendChild(myScript);
    

    If you do it this way, you'll be an outlaw. The table manners and best practices crowd will shudder - that type is not in the spec - the computer will esplode!!. So you might as well use a 4 letter word for the type and giggle hysterically.

    Update

    also works with inline scripts.

提交回复
热议问题