Global variables in JS vs local storage vs values ​​in the DOM, which one will be more efficient?

What is the difference between Global variables in javascript and values ​​in page doc or values ​​in local storage?

Which option would be better if I need some variables that will be sent from the server side, for example php, for Front end technologies such as Angular / jquery like files, taking into account large variables ?

What will affect page performance ?

+7
source share
4 answers

Global variables

. , . , , .

myNamespace:

var myNamespace = window.myNamespace || {};
myNamespace.variable = 'Some value';

, JSON HTML script.

, PHP, , PHP json_encode:

<?php
  $book = array(
    "title" => "Eloquent JavaScript",
    "author" => "Marijn Haverbeke",
    "edition" => 2
  );
?>
<script>
var myNamespace = '<?php echo json_encode($book, JSON_PRETTY_PRINT) ?>';
/* var myNamespace = {
    "title": "Eloquent JavaScript",
    "author": "Marijn Haverbeke",
    "edition": 2
  };
*/
</script>

JSON_PRETTY_PRINT , JSON , , , , . , , JavaScript .

. myNamespace , IIFE, . window.myNamespace, , , myNamespace. AJAX .

var myNamespace = (function(namespace) {
  namespace.a = (function() { return ... })();
  namespace.b = (function() { return ... })();
  return namespace;
})(window.myNamespace || {});

AJAX .

DOM

DOM - HTML, .

<img src="path/to/image.jpg" id="myId" class="myClass" title="My title" data-owner="Joe Bloggs" data-year="2017" />

DOM , . , , document.getElement... DOM.

var attrs = document.getElementById('unique-id').attributes;
// returns NamedNodeMap {0: id, 1: class, 2: data-owner, 3: data-year, 4: title ...}

Array.prototype.slice.call , :

Array.prototype.slice.call(document.getElementById('myId').attributes)
    .forEach(function(item) {
      console.log(item.name + ': '+ item.value);
    });

// class: myClass
// data-owner: Joe Bloggs
// data-year: 2017
// id: myId
// src: path/to/image.jpg
// title: My title

LocalStorage

localStorage - / , , . " " - , .

cross-storage Zendesk .

> DOM > LocalStorage > AJAX

  • .
  • DOM , .
  • LocalStorage / .
  • AJAX , .
+8
  • → js
  • Localstorage → ( ).
+5

:

  • JS globals
  • DOM
  • localStorage sessionStorage

DOM Javascript / . - , , , . DOM , , , - (, / ) .

, - ( ).

localStorage, , . , , - , , , . , , .

Javascript , .

+5

This is more a matter of needs. If you want to use values ​​on all pages and persist between different sessions, it is recommended localStorage. However, if you want to destroy data between sessions, it is recommended to use sessionStorage. If you do not need DOM overhead, you can use variables. You can initialize them from the DOM, but not re-read from the DOM.

+3
source

Source: https://habr.com/ru/post/1666696/


All Articles