Preload script without execute

前端 未结 6 1859
生来不讨喜
生来不讨喜 2020-12-06 17:09

Problem

In order to improve the page performance I need to preload scripts that I will need to run on the bottom page.

I

6条回答
  •  太阳男子
    2020-12-06 17:37

    For each script you'd like to download without executing, make an object containing a name and a url, and put those objects into an array.

    Looping through the array, use jQuery.ajax with dataType: "text" to download your scripts as text. In the done handler of the ajax call, store the text content of the file (which is passed in first argument) in the appropriate object, increment a counter, and call an "alldone" function when that counter is equal to the number of files you are downloading in this manner.

    In the "alldone" function (or later) do the following: Loop through your array again, and for each entry, use document.createElement("script"), document.createTextNode(...), and (...scriptNode...).appendChild(...) to dynamically generate scripts having the intended source inline, rather than via "src" attribute. Finally, do document.head.appendChild(...scriptNode...), which is the point when that script is executed.

    I have used this technique in a project where I needed to use frames, where several frames and/or the frameset need identical JavaScript files, in order to make sure each of those files is requested only once from the server.

    Code (tested and working) follows

    
    
        
            
            
        
        
            
            
        
    
    

    other question closely related to above approach other related question

提交回复
热议问题