Search code examples
javascriptperformancecorrectness

Should all javascript be put inside a load() on body event?


Should I put all this inside a load() body event so that it loads after the page has rendered and the DOM objects have been created? (I did find I had to use .innerhtml rather than .value for it to work.) If so how...

(*I know this is rubbish code, but it is better than my last attempt and worse than my next attempt. Once I get some time to comeback to this I will recreate it using a literal constructor with internal functions. I am not looking to take this Javascript any further in functionality. The back-end php I have will handle security and checks)

<script type="text/javascript">

//To get the price of a product applying discount
function getPrice(location,quantity)
{
    //Get the product choice
    var e = document.getElementById("productList["+location+"]");
    var productSelected = e.options[e.selectedIndex].value;

    //TODO: Determine discounts based on product choice
    switch(productSelected)
    {
        case '0':
            return 0;
        case '1':
            return 10;
        case '2':
            return 15;
    }
    return null;
}

//To update product only
function updateProduct(location)
{
    updateRow(location,document.getElementById("quantity["+location+"]").value);
}

//To update only that row
function updateRow(location,quantity)
{
    //Check Quantity is a valid Number and also not a float or negative
    if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity) && (quantity >= 0)) {
        quantity = Math.floor(quantity);
    } else {
        quantity = 0;
    };

    //Update the quantity input field to whatever quantity is - Investigate later!
    document.getElementById("quantity["+location+"]").value = quantity;

    //Store old Price for changing total
    var oldTotal = document.getElementById("totalPrice").innerHTML;
    var oldLinePrice = document.getElementById("linePrice["+location+"]").innerHTML;

    //Calculate and Store Prices to adjust the total
    var productPrice = getPrice(location,quantity).toFixed(2);
    var newLinePrice = (quantity*productPrice).toFixed(2);

    //Apply  Updates
    document.getElementById("unitPrice["+location+"]").innerHTML = productPrice;
    document.getElementById("linePrice["+location+"]").innerHTML = newLinePrice;
    document.getElementById("totalPrice").innerHTML = (oldTotal-oldLinePrice+parseFloat(newLinePrice)).toFixed(2);
}
</script>

Solution

  • You only need to put any getElement calls, or calls to functions that get elements, in a load function.