Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

JS & Dom - Tips & Tricks #3

time to read 2 min | 376 words

As you might already know, your browser’s developer tools can be used to debug JavaScript by utilizing breakpoints. Breakpoints allow you to pause script execution as well as step into, out of, and over function calls. Breakpoints are added in your developer tools by means of line numbers where you indicate where you want script execution to be paused.

This is fine until you start changing your code. Now a defined breakpoint may no longer be in the place you want it to be. Take the following code as an example:

function doSomething() {
  console.log('first log...');
  console.log('last log...');
}

doSomething();

If I open this code in my browser’s developer tools debugger, I can place a breakpoint before one of the lines inside the doSomething() function. Let’s say I want to pause script execution before the “last log…” message. This would require that I place the breakpoint on that line. In this case, it would be line 3 of my code.

But what if I add the breakpoint, then I add another line of code before that line?

function doSomething() {
  console.log('first log...');
  console.log('second log...');
  console.log('last log...');
}

doSomething();

If I refresh the page, the breakpoint will still be there but now the script will pause execution on the “second log…” message instead of the “last log…” message. Again, this is because the breakpoints are based on line numbers. The debugger is still stopping on line 3, but that’s not what we want.

Enter JavaScript’s debugger statement.

Instead of setting breakpoints directly in the developer tools, I can use the debugger statement to tell the developer tools where to pause execution:

function doSomething() {
  console.log('first log...');
  debugger;
  console.log('last log...');
}

doSomething();

Now I can add as much code as I want prior to the debugger statement and the script will still pause in the right place, without any concerns over changing line numbers.

If you’ve been writing JavaScript for a while, I’m sure this tip is nothing new to you. But those new to debugging will certainly benefit from using this feature, which is part of the official ECMAScript spec. As expected, inserting a debugger statement will have no effect on your code if a debugger is not present (e.g. if the developer tools are not open).

JS & Dom - Tips & Tricks #2

time to read 2 min | 339 words

Last year, David Walsh published an article called 7 Essential JavaScript Functions where he shared some JavaScript utility/helper snippets. One of the interesting techniques used in one of the functions is where he gets the absolute URL for a page. He does this using something like the following:

var getAbsoluteUrl = (function() {
  var a;
  return function(url) {
    if(!a) a = document.createElement('a');
    a.href = url;
    return a.href;
  };
})();

// Usage
getAbsoluteUrl('/something'); // https ://example.com/something

This example reveals a clever little technique. Basically, this function takes advantage of JavaScript’s ability to create elements that don’t actually exist in the DOM. From there, you can get info from that element as you please. In this case, the desired result is the full URL of the page. The browser automatically fills out full URLs in the href value of links, even if they’re written in relative format. So with this we can easily grab the full URL from just a relative page link.

Similarly, someone in the comments posted the following snippet:

function isValidEmail(string) {
  string = string||'';
  var lastseg = (string.split('@')[1]||'').split('.')[1]||'',
      input = document.createElement('input');
      input.type = 'email';

  input.required = true;
  input.value = string;
  return !!(string && (input.validity &&
                       input.validity.valid) && 
                       lastseg.length);
}

console.log(isValidEmail('')); // -> false
console.log(isValidEmail('asda')); // -> false
console.log(isValidEmail('asda@gmail')); // -> false
console.log(isValidEmail('asda@gmail.com')); // -> true

There’s a lot going on there, but the principle is the same. The script creates an email input field, without actually inserting it into the page, and then information is gleaned from the input. The acquired info falls in line with what the browser would do if the email input actually existed and was interacted with on the page. This is along the same lines as what happens with feature detection using a library like Modernizr.

So the basic lesson here is, if you want to find out info on how a browser handles certain HTML elements, remember that those elements don’t actually have to be in the DOM. You can create them yourself and then run some tests and respond accordingly.

JS & Dom - Tips & Tricks #1

time to read 2 min | 320 words

There are many ways to read content from elements and nodes. Here’s another one that allows you to read and write an individual node’s value. It uses the nodeValue property of the Node interface. The nodeValue of an element will always return null, whereas text nodes, CDATA sections, comment nodes, and even attribute nodes will return the text value of the node. To demonstrate its use, I’ll use the following HTML:

<body class="home">
  <p>Example. <span>Example paragraph one.</span></p>
  <p>Example paragraph two.</p>
  <p>Example paragraph three.</p>
  <p>Example paragraph four.</p>
  <!-- comment text -->
</body>

Now I’ll run the following JavaScript to read/write a few of the nodes:

let b = document.body,
    p1 = document.querySelector('p');

// reading node values
console.log(b.nodeValue); // null for all elements
console.log(b.attributes[0].nodeValue); // "home"
console.log(b.childNodes[7].nodeValue); // " comment text "

// changing nodeValue of first node inside first paragraph p1.firstChild.nodeValue = 'inserted text<br>';

Notice the second console.log is displaying the text of an attribute node. This would be the equivalent of using getAttribute(), with the difference being that getAttribute() acts on elements, whereas nodeValue can be applied to any type of node.

Also notice that I’m using nodeValue to read the contents of an HTML comment. This is one of many ways you can do this. This would be the equivalent of reading the textContent property or data property of the comment node. As you can see from the final line in that code example, I’m able to define the nodeValue of one of the text nodes, so this isn’t read-only.

A few other things to note regarding defining the nodeValue property: Setting nodeValue will return the value that was set, and you cannot set the nodeValue when the nodeValue is null (unless of course you change it to null, which is the same as an empty string that’s changeable later).

MDN’s article on nodeValue has a chart that lists the different node types and what their nodeValue will return.

Minifying Your JavaScript with Uglify

time to read 2 min | 313 words

Do your web visitor a favor with faster website

Programmer biasanya selalu memperhatikan performa dari kode yang mereka hasilkan. Akan tetapi membuat kode javascript yang berjalan di sisi klien membutuhkan perhatian lebih.

Browser yang kita gunakan tidak dapat menampilkan apapun hasil pekerjaan kamu jika javascriptnya belum terdownload ke browser. Sungguh sangatlah penting untuk mempercepat javascript terdownload secepat mungkin agar website tidak terasa lemot.

Salah satu hal yang bisa kamu lakukan untuk mempercepat javascript terdownload ke browser adalah dengan memperkecil ukurannya.

(function() {
    var process = "minification";
    var tool = "Uglify";

    function logProcess () {
        console.log(process);
    }

    logProcess();
    // => "minification"
})();

Contoh kode javascript ini dapat diperkecil ukurannya menjadi seperti ini

!function(){function n(){console.log(i)}var i="minification";n()}();

Walaupun kodenya terlihat sangat berbeda, javascript engine melakukan hal yang sama. Kode ini diperoleh dengan melakukan beberapa hal seperti :

  • Menghilangkan whitespace.
  • Menghilangkan komentar.
  • Mengubah nama variabel dan fungsi menjadi lebih pendek.
  • Menggunakan sintaks IIFE yang lebih concise
  • Membuang variabel yang tidak digunakan (variabel tool pada contoh diatas).

Ada cukup banyak tools untuk memperkecil ukuran javascript, tetapi yang paling mudah digunakan adalah UglifyJS. Untuk memulai menggunakannya

  1. Pastikan Node JS sudah terinstall.
  2. Jalankan sudo npm install -g uglify-js di terminal kamu.

Kamu akan dapat menggunakan UglifyJS dengan perintah berikut

uglifyjs myfile.js --output myfile.min.js  

Pada setting defaultnya, UglifyJS hanya akan melakukan minification sederhana dengan menghilangkan whitespace dan komentar saja. Untuk hasil lebih baik kamu bisa menambahkan flag ini.
1. --mangle akan mengubah nama variabel dan fungsi menjadi lebih pendek
2. --compress akan melakukan optimasi dan membuang variabel yang tidak digunakan.

Menggunakan kedua flag tersebut menghasilkan perintah seperti ini

uglifyjs myfile.js --output myfile.min.js --mangle --compress  

UglifyJS juga memiliki kemampuan untuk mengecilkan banyak file sekaligus dan menggabungkannya menjadi 1 file dengan perintah berikut.

uglifyjs folderJS/*.js --output all.min.js --mangle --compress  

Untuk cara penggunaan yang lebih detil, kamu bisa lihat disini.

Sekarang, kamu sudah punya tambahan tool yang solid. Waktunya membuat website yang lebih cepat!

Bundled Javascript di Yii Framework

time to read 2 min | 291 words

Ga perlu include jquery lagi.

Tahu gak sih kamu kalau Yii Framework telah menyediakan beberapa file JavaScript di dalam paketnya? Jadi kalau kamu ingin menyertakan sebuah file JavaScript ke dalam projek Web, kamu mungkin bisa cek dulu apakah Yii sudah punya JavaScript itu atau belum. Jika sudah ada, maka kamu gak perlu download dan manual meng-include JavaScript tersebut lagi, tetapi cukup memanggil fungsi di Yii saja.

Yii mempunyai beberapa JavaScript berguna yang siap dipakai di dalam sistemnya. Contohnya Jquery dan JQuery UI. Misalnya kamu perlu menggunakan Jquery UI, maka kamu cukup menulis sintaks di bawah untuk meng-include-nya

Yii::app()->clientScript->registerCoreScript(‘jquery.ui’);  

Untuk mengetahui Yii memiliki script inti apa saja, kita bisa mengecek di folder Yii Framework sendiri, tepatnya di framework/web/js/packages.php. Berikut beberapa file JavaScript yang terdapat di dalam Yii Framework:

  • jquery: Ini merupakan file jQuery yang terkenal itu. Secara default, Yii akan menggunakan file jQuery yang sudah terkompres. Hanya pada saat kondisi debug, Yii meng-include file jQuery biasa.

  • multifile: Berfungsi sebagai upload beberapa file. Multifile di Yii menggunakan jQuery plugin multiple file upload dari Fynework.com. Biasanya kita tidak akan meng-include manual file ini, karena JavaScript ini dipakai CMultiFileUpload.

  • cookie: Untuk mengatur cookie di jQuery. File JavaScript ini diambil dari jQuery-Cookie Klaus Hartl.

    jquery.ui: jQuery User Interface memiliki segudang fungsi UI seperti kalender, fungsi drag dan drop, fungsi autocomplete dan lain-lain yang berbasis jQuery.

  • metadata: Salah satu plugin jQuery. Fungsinya mengambil nilai metadata dari sembarang atribut ataupun kelas. Jika ingin tahu lebih lanjut silahkan kunjungi situs jQueryMetadata.

Sebenarnya script-script inti ini ada, dikarenakan Yii sendiri juga memerlukannya. Misalnya ada sebuah script inti yang bernama rating yang sebetulnya digunakan oleh CStarRating. Tetapi kita bisa saja include sendiri karena memerlukannya untuk kasus tertentu. Biasanya saya pribadi pada umumnya hanya membutuhkan jquery dan jquery.ui. Kalau kamu sendiri bagaimana?

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha