#TIL : JSON Parse is faster than Javascript Object declaration

TLDR;

Use JSON.parse("[your data in json string]") if your data is big (>10KB for instance)

Short Explaination :

JSON.parse parses a string to object, so it has many strict requirements than Javascript parses the source code (more syntax, more context)

Long Explaination :

https://www.youtube.com/watch?v=ff4fgQxPaO0

#TIL : Critical notice of string DOM manipulation using jQuery

Sometimes you want to manipulate the HTML DOM elements inside as a string, then you found a lot of HTML parser or DOM library from the Internet (but it supports only NodeJS). How to do it in a browser ?

The answer is “jQuery is your best friend in browser environment” :)

Then you try this :

1
2
3
4
5
const content = jQuery('<p><strong>Hello</strong></p><p>from</p><p><strong>KhanhIceTea</strong></p>');
content.find('p > strong').each(function(i, ele) {
$(ele).css('color', 'red');
});
console.log(content.html());

What you expected

1
<p><strong style="color: red;">Hello</strong></p><p>from</p><p><strong style="color: red;">KhanhIceTea</strong></p>

But the console print

1
<strong>Hello</strong>

SURPRISE !?? JQUERY SUCKS ?

Nope ! The reason is simple, DOM data structure is a tree. And, any tree has a root, right ??? Now you understand the problem ? Then we fix it below

1
2
3
4
5
6
7
8
const html_content = '<p><strong>Hello</strong></p><p>from</p><p><strong>KhanhIceTea</strong></p>';
// Wrap all elements into one root element (div)
const content = jQuery('<div />').append(html_content);
// or const content = jQuery('<div>' + html_content + '</div>');
content.find('p > strong').each(function(i, ele) {
$(ele).css('color', 'red');
});
console.log(content.html());

#TIL : View function source in developer tool console

If you are in console of developer tool and you want to know what the function does, you can view its source by:

  1. call .toSource() of variable or function name in Firefox

Example :

1
2
3
4
>> function hello(name) { return "Hello " + name; }

>> hello.toSource();
<- "function hello(name) { return \"Hello \" + name; }"
  1. click ‘show function definition’ in Chrome

show function definition

#TIL : View all parameters passed to callback function without reading docs

Time before, I often meet the situation that I forgot the parameters pass to a function (so I have to searching the API docs to read via Google). This progress can take you huge time if it repeats many times.

So I think one way to debug the parameters without reading API docs, that is pass console.log as a callback function parameter.

Examples :

1
2
3
4
5
6
[3,9,27].forEach(console.log);
// So you will get
// 3 0
// 9 1
// 27 2
// Then you know , first parameter is item, second parameter is indexed key
1
jQuery.ajax('/data.json').done(console.log).fail(console.error);

#TIL : Detect HTTP Response 304 Status Code in AJAX

Sometimes, you have a interval timer to retrieve new data updates from AJAX requests. But even the response status code of response is 304 (no body), the browser will treat it as 200 response and copy the cached body from browser cache to response body. So it will trigger the re-rederning UI components.

The way we can detect it is via its response headers list.

This example is using fetch API (which is supported in major browsers nowaday)

1
2
3
4
5
6
7
8
9
10
11
12
13
fetch('https://some.thing/has/data')
.then(function (res) {
if (res.headers.get('status') == '304 Not Modified') {
return null;
}
return res.json();
})
.then(function (data) {
if (data == null) return;

// Render your data below
renderUI(data);
});

#TIL : Trigger event after setting val in jQuery

After setting value of an input via val method, we should call the change chaining method to trigger the onChange event of element.

1
2
3
4
5
6
7
$('#selectCity').change(function() {
console.log($(this).val());
});

$('#selectCity').val('HaNoi'); // No trigger

$('#selectCity').val('HoChiMinh').change(); // Fire trigger

#TIL : Tracking changes of cookie on webpage

Using Object.defineProperty helper function as I wrote 3 days ago. We could track the changes of cookie on webpage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Based on Vlad Shevchenko's script at https://stackoverflow.com/a/36826049

var cookieSetterOrig = document.__lookupSetter__("cookie"); // get origin setter function
var cookieGetterOrig = document.__lookupGetter__("cookie"); // get origin getter function
Object.defineProperty(document, "cookie", {
get: function () {
console.trace();
return cookieGetterOrig.apply(document);
},
set: function () {
console.log(arguments);
console.trace();
return cookieSetterOrig.apply(document, arguments);
},
configurable: true
});

Notice : This code only works if cookie is changed by javascript, not http header request !