loading javascript dependencies on demand

后端 未结 6 1613
灰色年华
灰色年华 2020-12-14 23:15

I\'m sure there are different approaches to this problem, and I can think of some. But I\'d like to hear other people\'s opinion on this. To be more specific I\'ve built a w

6条回答
  •  心在旅途
    2020-12-14 23:54

    Gaia Ajax does this (I know since I implemented it - I'm the original founder) and they're GPL. So unless you're afraid they'll sue you (they're FUDding me with lawsuits now) you might want to check out how they do it. Basic technology is to inject a script tag using DOM when script is needed. Though you must take care NOT to reference stuff in this file before it is finished loading (which happens asynchronously)

    The solution to that problem (one solution) is to add up a variable at the bottom of the file and use recursive setTimeout calls to check if the variable is defined and defer execution of the code depending on the file being finished loading until that "bottom of JS file" variable is defined...

    We actually also tracked which files where included by appending the hashed value of the filenames into a hidden field on the page. This means we never ended up including the same file more then once...

    Pretty nifty in fact...

提交回复
热议问题