First, object detection (whether the JS method is supported): only if the method is supported to invoke
if (!getelementbyid | | getElementsByTagName) { returnfalse;}
Second, performance test filter
1. Minimize access to the DOM and minimize markup: Take the following code as an example
if (document.getElementsByTagName ("a"). Length > 0) { var aliks = document.getElementsByTagName ("a"); for (var i = 0; i < aliks.length; i++) { }}
This code is to find the <a> element in the DOM. If it is greater than 0, the number of <a> is obtained and iterated through. Here, two times, document.getElementsByTagName is used, and whenever you query an element in the DOM, the entire dom tree is searched, so this code performs a search more than once.
Optimized code:
var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) { for (var i = 0; i < aliks. length; i++) { }}
Iii. merging and placing scripts
<srcript src= "Js/a.js" ></script>
More use of external JS reference and the combination of multiple JS files into one, both can be pooled and reduce the number of requests sent when the page is loaded.
Iv. Compression Scripts
// get an array of objects var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) { // loops through for (var i = 0; i < Aliks. Length i++) { }}
After compression:
var aliks = document.getElementsByTagName ("a"); if (Aliks.length > 0) {for (var i = 0; i < aliks. length; i++) {}}
The streamlined script can reduce the size of the script although it does not understand it very well. In most cases we should have two versions of the script, a developed version with formatting and annotations that is easy to read, and a compact lite to be placed on the site.
JavaScript DOM programming art (Detection and performance optimization)