Search code examples
jqueryload

Jquery functions (file loading) in order


I'm using the code below to load files in order and on page load. But I getting the

$ is not a function

error for the last file "scripts.js". In other words, jquery and bootstrap files always load correctly, but the last file (my custom scripts) shows the error and nothing custom made works. What am I doing worng? Thanks for any help :)

<script type="text/javascript">
function chamajquery() {
    var element = document.createElement("script");
    element.src = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/jquery-3.6.0.min.js";
    document.body.appendChild(element);
    chamabootstrap();
}
function chamabootstrap() {
    var element2 = document.createElement("script");
    element2.src = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/bootstrap.bundle.min.js";
    document.body.appendChild(element2);
    chamascriptsmanuais();
}
function chamascriptsmanuais() {
    var element3 = document.createElement("script");
    element3.src = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/scripts.js";
    document.body.appendChild(element3);
}
window.addEventListener("load", chamajquery);

Solution

    1. I would expect the scripts to be appended to head and not body
    2. Your issue could be a timing issue
    3. Why use this convoluted way? If you want to make the page load faster, just add all 3 scripts just before the </body> tag

    <script src="<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/jquery-3.6.0.min.js"></script>
    <script src="<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/bootstrap.bundle.min.js"></script>
    <script src="<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/scripts.js"></script>
    </body>
    

    Alternative using onload (can be changed to addEventListener)

    <script type="text/javascript">
    function chamajquery() {
        const element1 = document.createElement("script");
        element1.onload=chamabootstrap;
        element1.src1 = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/jquery-3.6.0.min.js";
        document.querySelector("head").appendChild(element1);
    }
    function chamabootstrap() {
        const element2 = document.createElement("script");
        element2.onload=chamascriptsmanuais;
        element2.src = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/bootstrap.bundle.min.js";
        document.querySelector("head").appendChild(element2);
    }
    function chamascriptsmanuais() {
        const element3 = document.createElement("script");
        element3.src = "<?php echo esc_url(get_template_directory_uri()); ?>/assets/js/scripts.js";
        document.querySelector("head").appendChild(element3);
    }
    window.addEventListener("load", chamajquery);