clusterBuddy clusterBuddy - 4 months ago 23
Javascript Question

Why does a JSON data-url for table loads last in the DOM?

In reference to a simple HTML table as this:

<table id="table1"
data-toggle="table"
data-url="data1.json"
data-pagination="true"
data-sort-order="desc">


Can I change the JSON data call from table to precede the javascripts?

I am trying to implement some jquery conditional formatting and I'm noticing that even though I've put my scripts at the bottom, well below the
table
element, the DOM loads the JSON data last, where i'm suspecting that is why my conditional format is not applying (kindly ratify this in general, if specifics are needed, I'll post my code.)


I've added the whole code due to comment requests.


Here is the full code:
HTML:

<table id="table1"
data-toggle="table"
data-url="data1.json"
data-pagination="true"
data-sort-order="desc">
<thead>
<tr>
<th data-sortable="true" data-field="name" >Name</th>
<th data-sortable="true" data-field="W">Width</th>
<th data-sortable="true" data-field="H">Height</th>
<th data-sortable="true" data-field="D">Depth</th>
</tr>
</thead>
</table>


data1.json:

[{
"name": "First Value",
"W": 1,
"H": 10,
"D": 100
},{
"name": "First Value",
"W": 1,
"H": 10,
"D": 100
},{
"name": "First Value",
"W": 0,
"H": 10,
"D": 100
},...


Javascript/JQuery:

$(document).ready(function(){
$('td:nth-child(2)').each(function() {
var fValue = this.text();
if (fValue == 0) {
var oTableRow = $(this).parent();
oTableRow.css('background-color', 'red');
}
});
});

Answer

The problem you're having is that you are loading the data asynchronously, and changing your script order to fix it will only further introduce race conditions. The best way to solve this is to have a hook into when the data has loaded. you can do this 2 ways, either by manually calling your json via ajax and then loading the table so you have a callback when it is loaded. The second option which I think is your best option, is to use the event emitted by bootstrap table which is onLoadSuccess.

$('#table1').on('load-success.bs.table', function (e, arg1, arg2, ...) {
    // your jquery modifications go here
});