How to have a script in the <head> add script at the end of the <body>

后端 未结 5 1460
深忆病人
深忆病人 2020-12-07 00:51

A client is using Sharetribe which allows you add custom JS via admin, but only in the head. I want my script to load after jQuery, but jQuery is loaded at the end of the bo

相关标签:
5条回答
  • 2020-12-07 00:58

    $(document).ready(){} is executed when your dom element render successfully.

    0 讨论(0)
  • 2020-12-07 01:09

    Use DOMContentLoaded event:

    The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

    document.addEventListener("DOMContentLoaded", function (event) {
      console.log("DOM fully loaded and parsed");
    
      // Your code here
    });
    

    DOMContentLoaded is same as ready event of jQuery.

    Documentation

    0 讨论(0)
  • 2020-12-07 01:14

    As you're waiting for jQuery to load, you can simply wrap your code within jQuery's $(document).ready() method:

    $(document).ready(function() {
        // Your code here.
    });
    

    A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

    I realise that you've mentioned that you want this in "vanilla" JS, but as you're waiting for jQuery to load anyway this seems a bit redundant.

    0 讨论(0)
  • 2020-12-07 01:16

    Tell your code to wait for the DOM to finish loading:

    window.onload = function() {        
        var script   = document.createElement("script");
        script.type  = "text/javascript";
        //....
    }
    

    Or using jQuery:

    $(document).ready(function() {
        var script   = document.createElement("script");
        script.type  = "text/javascript";
        //....
    });
    
    0 讨论(0)
  • 2020-12-07 01:18

    When the browser run your code in <head>, the <body> element didn't existed yet. So, document.body was null.

    To create a script a the <body> element, use 'load' event of document, for example:

    .............
    document.addEventListener('load', function(event){
       var script = document.createElement('script');
       ...............
       document.body.appendChild(script);
    }, false);
    ............
    
    0 讨论(0)
提交回复
热议问题