Javascript 文件加载回退。替代 document.write()

您可能熟悉旧的 Jquery 负载回退:


<script>window.jQuery || document.write('<script src="https://example.com/jquery.js"></script>')</script>

但我在这里和那里读到:不要使用document.write,对你的健康有害,它在 Chrome 上不起作用(它对我有用,Chrome 78)。

所以我试图替换它,但我无法找到一个解决方案,在DOM加载被触发之前同步加载新的 js 文件。

最终发生的DOM操作替代方案是浏览器认为DOM已加载并且所有$(document).ready()失败并显示“ $ 未定义”。


function Jqfallback() { 

    var j = document.createElement('script');    

    j.src = 'https://example.com/jquery.js'; 

    document.getElementsByTagName('head')[0].appendChild(j); 

}

(window.jQuery || Jqfallback() );

无论我把这个脚本或新的 JS 文件放在哪里,在这种情况下,它('head')[0]已经在正文中的所有其他 JS 之前,它会“异步”加载它。


还有其他选择还是我document.write()在 2019 年末继续摇摆不定?


慕后森
浏览 188回答 2
2回答

喵喵时光机

加载和解析 JQuery 需要一些时间。因此,在附加脚本后使用(小)超时。此代码段将条件加载包装在立即执行的匿名函数中:(myScripting => {&nbsp; &nbsp; if (!window.$) {&nbsp;&nbsp; &nbsp; &nbsp; let j = document.createElement('script');&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; j.src = '//code.jquery.com/jquery-3.4.1.slim.min.js';&nbsp;&nbsp; &nbsp; &nbsp; document.querySelector('head').appendChild(j);&nbsp; &nbsp; &nbsp; setTimeout( myScripting, 200 );&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; myScripting();&nbsp; &nbsp; }})(JqIsLoadedSoMyScriptingCanStart);// put your main scripting in herefunction JqIsLoadedSoMyScriptingCanStart() {&nbsp; // extra check&nbsp; if (!window.$) {&nbsp; &nbsp; alert("Sorry, JQuery is not loaded, can't continue");&nbsp; &nbsp; return;&nbsp; }&nbsp; console.log("JQuery in place?");&nbsp; console.log($("head script")[1]);}<script src="cantLoadThis"></script>

Helenr

将使用 jQuery 的代码放在onload()函数中。var jQuery1 = document.createElement('script');jQuery1.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";jQuery1.onload = function () {&nbsp; &nbsp; &nbsp; &nbsp; var $ = window.jQuery;&nbsp; &nbsp; &nbsp; &nbsp; $.when(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$.getScript("https://someOtherScript.js"),&nbsp; //if you need&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$.Deferred(function (deferred) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$(deferred.resolve);&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; ).done(function () {&nbsp; &nbsp; &nbsp; &nbsp; console.log("all scripts loaded!!");&nbsp; &nbsp; &nbsp; &nbsp; doNextTask(); //some other code which uses jQuery});};在onreadystatechange中将 jQuery 附加到您的文档中document.onreadystatechange = function () {&nbsp;if (document.readyState == "complete") {&nbsp; &nbsp; // document is ready.&nbsp;&nbsp; &nbsp; document.head.appendChild(jQuery1);&nbsp;}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript