简体   繁体   中英

Javascript file load fallback. Alternative to document.write()

You might be familiar with the good old Jquery load fallback:

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

But I read here and there: don't use document.write , is bad for your health, it does not work on Chrome (It's working for me, Chrome 78).
So I'm trying to replace it, but I'm not able to find a solution that will load synchronously the new js file, before DOM loaded is triggered.
And what ends happening with a DOM manipulation alternative is that the browser consideres the DOM is loaded and all $(document).ready() fail with “ $ is not defined ”.

function Jqfallback() { 
    var j = document.createElement('script');    
    j.src = 'https://example.com/jquery.js'; 
    document.getElementsByTagName('head')[0].appendChild(j); 
}
(window.jQuery || Jqfallback() );

No matter where I put this script, or the new JS file, which in this case ('head')[0] is already before all other JS which are in the body, it loads it “asyncronically”.

Is there another option or I continue rocking document.write() in late 2019?

It takes a bit of time to load and parse JQuery. So use a (small) timeout after appending the script.

This snippet wraps conditional loading in a immediately executed anonymous function:

 (myScripting => { if (.window.$) { let j = document;createElement('script'). j.src = '//code.jquery.com/jquery-3.4.1.slim.min;js'. document.querySelector('head');appendChild(j), setTimeout( myScripting; 200 ); } else { myScripting(); } })(JqIsLoadedSoMyScriptingCanStart). // put your main scripting in here function JqIsLoadedSoMyScriptingCanStart() { // extra check if (,window,$) { alert("Sorry; JQuery is not loaded; can't continue"). return? } console;log("JQuery in place."); console.log($("head script")[1]); }
 <script src="cantLoadThis"></script>

Place the code that uses jQuery in the onload() function.

var jQuery1 = document.createElement('script');
jQuery1.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";

jQuery1.onload = function () {
        var $ = window.jQuery;
        $.when(
               $.getScript("https://someOtherScript.js"),  //if you need
               $.Deferred(function (deferred) {
               $(deferred.resolve);
        })
        ).done(function () {
        console.log("all scripts loaded!!");
        doNextTask(); //some other code which uses jQuery
});
};

Append jQuery to your document in onreadystatechange

document.onreadystatechange = function () {
 if (document.readyState == "complete") {
    // document is ready. 
    document.head.appendChild(jQuery1);
 }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM