<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var $jq331 = $.noConflict(true);
</script>
<div id="box" style="background:#555;color:#FFF;position:absolute;left:0;top:0;width:400px;height:100px;</div>
var elem = document.getElementById('box');
console.log("elem", elem);
console.log("jq", $jq331);
var jqElem = $jq331('#box')
console.log("jqElem", jqElem);
elem.style.cssText +=';width:300px;height:50px;';
elem.style.width = '300px';
elem.style.height = '50px';
elem.style.top = '40px';
elem.style.left = '90px';
jqElem.css({ 'width': 300, 'height': 50, 'top':40, 'left': 90 });
Object.assign(elem.style,{width:"300px",height:"50px",top:"40px",left:"90px"});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
cssText | |
style | |
jquery | |
object |
Test name | Executions per second |
---|---|
cssText | 41519.0 Ops/sec |
style | 268486.9 Ops/sec |
jquery | 56330.2 Ops/sec |
object | 299691.3 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, the options compared, pros and cons of each approach, and other considerations.
Benchmark Overview
The provided benchmark measures the performance of different approaches for updating CSS styles on an HTML element. The test case uses jQuery, a popular JavaScript library, to manipulate the DOM.
Script Preparation Code
The script preparation code sets up the necessary variables and includes the jQuery library:
var elem = document.getElementById('box');
console.log("elem", elem);
console.log("jq", $jq331);
var jqElem = $jq331('#box')
console.log("jqElem", jqElem);
The $jq331
variable is created by calling $.noConflict(true)
before loading the jQuery library. This is a common practice to avoid conflicts with other libraries.
Html Preparation Code
The HTML preparation code includes the necessary CSS styles and a <div>
element with an ID of "box":
<div id="box" style="background:#555;color:#FFF;position:absolute;left:0;top:0;width:400px;height:100px;</div>
Individual Test Cases
There are four test cases, each measuring the performance of a different approach:
style
property of the element using string concatenation.jqElem.css()
).Object.assign()
to update the CSS styles on the element's style object.Pros and Cons of Each Approach
Here's a brief summary of each approach:
Object.assign()
. However, it provides a convenient and easy-to-use API for DOM manipulation.Object.assign()
is faster than concatenating strings or using jQuery's CSS methods, as it updates the existing style object in a single operation.Considerations
Alternatives
If you're looking for alternative approaches, you can consider:
style
property directly on the element: This approach avoids the overhead of creating a new object and updating the existing style.