jqueryfunctionjquery-3

Run inline jQuery after jQuery-library is fully loaded at the bottom of the document?


I have a big inline jQuery function that I want to trigger after the jQuery library is loaded at the bottom. Otherwise I'd get the "Uncaught ReferenceError". Therefore I wrapped the function into a timeout-function - which works, but only as long as the DOM is loaded faster than the timout takes. I already tried window-on-load-function, whicht gives me back "Uncaught ReferenceError" as well.

HTML-Document looks like this:

<html>
<head>
...
</head>
<body>
...
<script>

    // Inline jQuery that needs to stay inline

    setTimeout( function(){ 

        // Run my big jQuery function

    }, 100 );

</script>
...
<script src="jQuery-library.js" ><script>
<script src="my-jQuery-functions.js" ><script>
</body>

Is there any way to trigger my inline-function after the jQuery-library in the documents bottom is loaded completely, and possibly WITHOUT moving jQuery-library to the head? Thank you very much in advance!


Solution

  • You can react to the load event, which occurs after all resources (scripts, images, etc) have finished loading:

    <script>
    window.addEventListener("load", function () {
      $(function () {
          $("body").append("<p>jQuery is available now!</p>");
          
          // Run my big jQuery function
      });
    }, false);
    </script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>