Vian Ojeda Garcia
Vian Ojeda Garcia

Reputation: 867

How to load javascript file1 first before javascript file2

I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

<body>
    <script src="../script/Main%20Functions.js"></script>
    <script src="../script/Main-events.js"></script>
</body>

Main Functions.js

checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}

Main-events.js

const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?

Upvotes: 1

Views: 89

Answers (2)

Shubham Sharma
Shubham Sharma

Reputation: 315

If you want to load another js file in your ajax call than you can use this

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}

and use it like:

if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});

or simply

You can listen to the script's load event, and do things with the results as you would. So:

var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes

Another option

will fire when a script is finished loading.

You will not be able to do something like:

<script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will not do what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.

Upvotes: 1

nikamanish
nikamanish

Reputation: 772

ajax is Asynchronous Javascript and XML.

So, being asynchronous, the console.log are not being called in order. And as ajax might be taking a while to get called, the 'ok2' is getting called first.

The solution to this is to call the 'ok2' inside the success or done method of $.ajax

Upvotes: 1

Related Questions