What is the most efficient way to grab multiple meta tag values using jQuery? I'm storing some values in meta tags that I want to read in via jQuery and either pass along to ajax calls or make changes to the UI based on. The code base I'm working on currently has this...
params: {
ad_hash: $('meta[property=ad_hash]').attr('content'),
ad_id: $('meta[property=ad_id]').attr('content'),
ad_advertiser_id: $('meta[property=ad_advertiser_id]').attr('content'),
ad_subcategory_id: $('meta[property=ad_subcategory_id]').attr('content'),
ad_est_firstoccur: $('meta[property=ad_est_firstoccur]').attr('content'),
ad_est_lastoccur: $('meta[property=ad_est_lastoccur]').attr('content'),
ad_firstoccur: $('meta[property=ad_firstoccur]').attr('content'),
ad_lastoccur: $('meta[property=ad_lastoccur]').attr('content'),
ad_time: $('meta[property=ad_time]').attr('content'),
ad_timestamp: $('meta[property=ad_timestamp]').attr('content'),
ad_rating: $('meta[property=ad_rating]').attr('content'),
hostname: $('meta[property=hostname]').attr('content'),
user_clientip: $('meta[property=user_clientip]').attr('content'),
user_searchterm: $('meta[property=user_searchterm]').attr('content'),
user_voted: $('meta[property=user_voted]').attr('content'),
trans_recentlyaired: $('meta[property=trans_recentlyaired]').attr('content'),
trans_lastaired: $('meta[property=trans_lastaired]').attr('content'),
trans_on: $('meta[property=trans_on]').attr('content'),
trans_during: $('meta[property=trans_during]').attr('content'),
trans_tobeaired: $('meta[property=trans_tobeaired]').attr('content')
},
Is there a more efficient way to grab multiple meta tag values than making multiple trips to the dom? Here are some alternate solutions I've considered...
Using a JSON string would be more efficient size-wise, but essentially you're just parsing XML data. You could loop through the meta
tags, in order to reduce how often you select from the DOM, and to make your code more dynamic:
var params = {};
$('head meta[property][content]').each(function() {
params[$(this).attr('property')] = $(this).attr('content');
});