css - Is looping through all style sheets and classes a good idea in JavaScript? -
i have javascript function given in code below, in asp.net webforms page i.e. in aspx page.
the code implements logic need in app i.e. find css class, concerned if there many style sheets/classes there many iterations done resulting in slower performance on client-side.
in code, first style sheets obtained, , each style sheet classes obtained iterated find given class.
question: concern slow performance valid when there many style sheets/classes, , if yes, there quicker way find css class using javascript?
function getstyle(classname) { var stylesheets = document.stylesheets; var stylesheetslength = stylesheets.length; (var = 0; < stylesheetslength; i++) { var classes = stylesheets[i].rules || stylesheets[i].cssrules; var classeslength = classes.length; (var x = 0; x < classeslength; x++) { if (classes[x].selectortext === undefined) { continue; } if (classes[x].selectortext == classname || classes[x].selectortext.indexof(classname) >= 0) { if (classes[x].csstext) { return classes[x].csstext; } else { return classes[x].style.csstext; } } } } }
update 1
i providing code app illustrate use of above javascript method. have no control on classes being used since coming third-party controls in asp.net page.
if ("none" === getstyleattribute(getstyle(".rwdialog"), "background-image")) { alldivs[i].style.paddingleft = "5px"; }
using long i think fool-proof supporting strings , stuff regexs can try:
function getitem(selector, item, sheet) { var group = sheet.substr(sheet.indexof(selector)).match(/{(?:(["'])((?:(?=(?:\\)*)\\.|.)*?)\1|[\s\s])*?}/)[0]; return group.substr(group.indexof(item)).match(/\s*:\s*((?:(?=(["'])((?:(?=(?:\\)*)\\.|.)*?)\1).*|.)*?);/)[1].trim(); }
now put @ beginning of document:
function loadstylesheets(url, callback) { var xhr = new xmlhttprequest(); xhr.onreadystatechange = function () { if (xhr.readystate === 4) { callback(xhr.responsetext); } }; xhr.open("get", url); xhr.send(); }
now:
loadstylesheets("path/to/style/sheet", function (text) { alert(getitem('.class1', 'background-image', text)); });
Comments
Post a Comment