📜 ⬆️ ⬇️

Extending jQuery style functionality

When working with jQuery, a slight inconvenience is the application of a large number of CSS rules to tags. The solution to this problem in most cases comes down to repeating $.(“”).css(“”, “”); That is not good, but a few lines of code corrected the situation.
How? We read below.

43 lines - all extension

The idea behind it is as follows:
Using regular expressions, we parse the CSS file for rules ( getStyles ), rules for property-value ( setStyle ), and apply to the loaded document.
And, actually, implementation.
$.fn.extend({
setStyle : function (selector, rulesString) {
var rules = (rulesString + ';' ).match( /([^:]+)\:([^\;]*)\;/gi );
for ( var id in rules) {
rules[id].replace( /[\s]*([^\s]+)[\s]*\:([^\;]*)\;/gi ,
function (rule, propery, value) {
$(selector).css(propery, value)
})
}
},
getStyles : function (styleRef){
var styles = styleRef.replace( /\/\*(.|\s)*?\*\//gi , "" , "$1" ).match( /[^\}]*\{([^\}]*)\}/gi );
for ( var id in styles) {
styles[id].replace( /\s+/gi , " " , "$1" ).replace( /([^\{]*)\{([^\}]+)\}/gi ,
function (style, selector, rules){
$.fn.setStyle(selector, rules)
});
}
},
_css : function (styleRef) {
if ( /.*\.css/gi .test(styleRef)) {
$.ajax({
type : "GET" ,
url : styleRef,
success : function (retValue) {
$.fn.getStyles(retValue)
},
error : false
})
} else if ( /[^\}]*\{([^\}]*)\}/gi .test(styleRef)) {
$.fn.getStyles(styleRef)
} else {
$.fn.setStyle( this .selector, styleRef)
}
return true
}
})

$.extend({
_css : function (styleRef) {
return $.fn._css(styleRef)
}
})
Colored with dumpz.org
In compressed form, the file weighs 700 bytes.

And what can it do?

Or maybe it is the following:

Testing and results

Testing was conducted on the set:

The essence of the test is as follows: in the theme of the selected CMS, there is only one file responsible for the styles - style.css , we style.css it with the script and without it, measuring time using the Chrome developer tools. We measure the work of the script by sending messages to the console like var currentDate = new Date(); console.log(" " + currentDate.getTime() + "ms"); var currentDate = new Date(); console.log(" " + currentDate.getTime() + "ms");
image
According to the results of several measurements, we estimate the download speed.
In the picture below on the left, data on the operation of the script, on the right, the css download time without it. Columns in order:
  1. Download speed from the Network page
  2. The speed measured by the messages of the console (for some reason, higher, although the measurement was made before and after the GET request)
  3. The speed with which the rules are applied to the document
  4. Amount
image
The difference in time turned out to be equal to 12%, which is approximately = 10ms, so we can say that the expansion work is not noticeable, at least in Chrome.

')

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


All Articles