document.createElement(“script”) synchronously

前端 未结 11 2326
执念已碎
执念已碎 2020-11-22 12:56

Is it possible to call in a .js file synchronously and then use it immediately afterward?



        
11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 13:57

    This isn't pretty, but it works:

    ');
    
    
    
    

    Or

    ');
      window.onload = function() {
        functionFromOther();
      };
    
    

    The script must be included either in a separate '); functionFromOther(); // Error

    The same can be done with creating a node, as Pointy did, but only in FF. You have no guarantee when the script will be ready in other browsers.

    Being an XML Purist I really hate this. But it does work predictably. You could easily wrap those ugly document.write()s so you don't have to look at them. You could even do tests and create a node and append it then fall back on document.write().

提交回复
热议问题