Home > database >  is nested function calling possible in jquery
is nested function calling possible in jquery

Time:01-23

I'm using a script to call a separate file and inside that file I'm calling another file.

The script I'm using to call is this:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" 
        integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 
        crossorigin="anonymous">
</script>

<script> 
    $(function(){
        $("#socials").load("sources/socials.html");
    });
</script>

<script> 
    $(function(){
        $("#icon").load("img/icon.xml");
    });
</script>

and I'm calling the file like this:

<div id="socials"></div>

and inside socials.html, I'm calling the icon.xml like this:

<div >
            <a href="mailto:[email protected]?" id="icon"></a>
        </div>

it's not working for me when I try it like this. Is it not possible to do or is this just the incorrect way?

EDIT I explained it in a comment below so I'll include the comment here too, I think it makes a little more sense what I'm trying to accomplish:

Essentially I have two standalone files that I am referencing, file A and file B. I am referencing file B inside of file A. When I reference file A in index.html, it works fine except that file B will not get referenced and I don't see the content of file B. BUT if I reference file A and file B directly in index.html without referencing, I can see the content of both files as expected

CodePudding user response:

.load() is asynchronous, and the second function isn't waiting for the first one to finish, so the #icon element isn't in the DOM when it runs. You need to do it in the callback function.

$(function() {
  $("#socials").load("sources/socials.html", function() {
    $("#icon").load("img/icon.xml");
  });
});
  •  Tags:  
  • Related