JavaScript - 如何以非异步方式加载外部脚本?

问题描述:

我正在查找允许我使用JavaScript以非异步方式加载其他JavaScript文件的代码。我试过这个:JavaScript - 如何以非异步方式加载外部脚本?

var script=document.createElement('script'); 
script.setAttribute("type","text/javascript"); 
script.setAttribute("src", "jquery.min.js"); 
document.getElementsByTagName("head")[0].appendChild(script); 

$("div.whatever").css("color","red"); 

但这并不奏效。它会插入脚本节点,但它会在jQuery加载之前继续运行脚本的其余部分。这最终失败,因为jQuery代码尝试运行时尚未由jQuery定义$

有没有办法来加载使用本地JS该脚本非异步?

+1

可能的重复:http://*.com/questions/3248384/document-createelementscript-synchronously – 2012-02-09 16:41:56

+0

可能的重复[动态加载JavaScript同步](http://*.com/questions/2879509/dynamically-loading- javascript-同步) – Bakudan 2012-02-09 16:42:49

+2

^- 可能重复的评论^^ – CompanyDroneFromSector7G 2012-02-09 16:44:08

您可以使用<script>节点.onload事件处理程序,继续/执行应脚本后执行任意代码装载,像

script.onload = function() { 
    // continune here 
}; 

,或者你可以尝试将async标志设置为false

script.setAttribute("async", false); 

虽然前者的解决方案中可用的任何浏览器实际上的作品,后者可能会不old'ish浏览器支持。

而是装载的同步,稍微好一点的想法可能是使用onload

script.onload = function() { 
    // $ is defined now 
}; 

// append it only now to make sure it does not load before setting onload 
document.getElementsByTagName("head")[0].appendChild(script);