我想加载一些更加动态的js文件,因此我使用带有类名称的div对象来包装检查脚本。在检查脚本检查特定的js文件未加载后,它会为父div创建一个新的外部js文件字符串。但是,什么也没发生。以下代码显示了我如何检查是否已加载js文件以及如何插入脚本字符串。但结果是只有jQuery is not loaded
被打印在控制台中。如何动态插入js文件
<div class="loadPagejQuery">
<script>
if (window.jQuery) {
// jQuery is loaded
console.log("jQuery is loaded ");
} else {
// jQuery is not loaded
console.log("jQuery is not loaded ");
(function() {
// Load the script
var script = document.createElement("SCRIPT");
script.src = '/Style/js/jquery-1.10.2.js';
script.type = 'text/javascript';
document.getElementsByClassName("loadPagejQuery")[0].appendChild(script);
})();
}
</script>
</div>
<script id="the_jquery_ui" src="/Style/jquery-ui-1.12.1/jquery-ui.js"></script>//Uncaught ReferenceError: $ is not defined
<link rel="stylesheet" type="text/css" href="/Style/jquery-ui-1.12.1/jquery-ui.css"/>
<script>
$(document).ready(function() {
//Uncaught ReferenceError: $ is not defined
});
</script>
你必须听'onload'事件,然后执行你的脚本... – Rayon
附加一个'onload'事件到你已经创建的脚本标记来加载jquery,并且在onload的回调函数中执行'.ready'功能。 –
如果在检查脚本之后插入外部js文件字符串,它会被执行吗? – MRWonderFuXker