It’s officially holiday-party season, meaning it’s time to whip out your most festive and glamorous cocktail attire. And sure, we all think we know what “cocktail attire” means — it’s what you wear to a wedding or an evening event that’s less formal than black tie, right? Sure. That’s one way to look at it. But the lines of what constitutes cocktail are a bit blurry because there really are no strict rules about what makes something cocktail-appropriate (apart from maybe not showing up in an over-the-top ball gown). But to simplify the cocktail-attire concept, there are certainly a few things to keep in mind when planning your looks. Below are a few tips and tricks to nailing this specific dress code for holiday parties and beyond.
From elegant dresses and stylish separates to standout accessories that are bound to set you apart from the rest, let the following selections be your contemporary guide to mastering the art of cocktail attire for all those winter weddings, festive feasts and any kind of holiday soirée.
So, you’re looking for the ultimate holiday party cocktail look?
Most people automatically default to a dress when they see the words “cocktail attire” on an invitation. It’s called a “cocktail dress” for a reason. Length doesn’t matter: a mini can be just as appropriate as something that skims the floor. The trick is to choose fabrics and or patterns that look refined — and more elegant than a basic cotton dress you run errands in. You want garments made of silk, chiffon, crepe, or something with a bold, rich pattern that feels luxe. And for the holidays especially, shine in something metallic or rock sparkling embellishments. Swishy fringe, sheer lace, and sequins are also a fabulous added touch.
There’s nothing like a full-on sequin dress for holiday and cocktail events, especially one like this spaghetti-strap navy number from J.Crew’s recent designer collaboration with Christopher John Rogers.
If you like playing with textures, this elegant knit and satin dress is a great option for the holiday season. The drop-waist dress features a voluminous balloon skirt and split-sleeve detail that is playful enough for any occasion.
A different sparkle and chiffon option from above, this ’90s-style, square neck dress is adorned with red poppy-shaped sequins. You can complete the look with either the matching mules or bag (if you want to go all out).
Make a statement in gold this season with this contrast knit and poplin fitted dress. The stretchy fabric of the bodice is not only comfortable but incredibly flattering.
You may be familiar with Loeffler Randall’s shoes and accessories, but don’t sleep on the brand’s ready-to-wear, which features an elegant collection of festive looks for the season like this balloon sleeve Red Silk Moire mini. Style the baby-doll dress with red tights or the brand’s matching silk moire mule.
There’s nothing like a cute and affordable cocktail dress like this velvet mini from Old Navy. Apart from the square neckline, it’s a good long-sleeve dress option in the winter, especially when its velvet.
If you’re looking for a sexy sheer party look that is sure to heads, try this lace and feathered mini dress by one of our favorite swimwear brands, Oséree.
Tip Two: Find Transitional Cocktail Pieces That You Can Wear Outside the Party
You don’t have to wear a dress. In fact, you can wear anything from a flowy maxi skirt and sleek trousers to a stylish blazer and a crisp silk top — versatile items that you can wear individually (and more casually) outside the champagne soirée! We also love any kind of matching set: silk, sequin, you name it. However, just like the tricks for a cocktail dress, you want to apply that same concept of finding elegant, refined statement pieces when styling separates for a cocktail look.
A chic blazer is always an easy way to look put together and classy with little to no effort. This maroon velvet blazer is not only elegant, it has a highbrow expensive feel but with a more affordable price tag that would make anyone feel merry.
Sheer and sequins is the pairing of the moment, which is why we love this layer skirt design from J.Crew. The silver sequin skirt underneath (which is removable) paired with the black chiffon overlay is a versatile and vibrant skirt and with some flashy depth.
When it comes to classy and sophisticated looks, you can’t go wrong with a tuxedo-style blazer — especially one in a crisp black-and-white color scheme. The best-selling, menswear-inspired piece is a cross between a jacket and a blazer, and made of warm wool, so you don’t have to worry about extra layers when out on the town in this look.
A pointelle sweater tank is a versatile wardrobe piece that can be worn year-round because its easy to layer and style. This one, in particular, features festive sparkles — ideal for the season — and if the red is a bit too Rudolph’s noise for you, the tank also comes in a cream-colored natural shade.
Another delicate sheer option to wear this season that can be styled a multitude of ways despite the sheer fabric. Wear it over tights and tucked into a sweater or blouse as seen here, or style it under a sleek blazer with some pumps or even tall boots.
Think smoking jacket with an elegant twist. If you like the idea of loungewear that can be dressed up, you’ll love this robe-style jacket by Rose Room. It can be worn a number of ways: tied in the front, the back, or worn open with another layer, plus it can easily transition from the office to the party. Complete the look with the matching silk trousers.
Depart from the typical holiday palette with this bright-pink sequin sweater from Farm Rio. The oversized floral turtleneck features a collarbone slit design and can be paired over the brand’s matching maxi dress for a fun double-sequin set.
Tip 3: Your Shoes Should Demand Attention — But Not Too Much
Now that fancy flats and sensible block heels are trendy, you don’t necessarily have to wear stilettos to your next party. Thank God. If you’re opting for a kitten-heel or lower mule style, try something with a bold color or embellishment. Especially if you plan to wear a classic black ensemble, adding a pop of color or sparkle with footwear is always a good idea. If you’re a tried and true Carrie Bradshaw stiletto girl, go ahead and rock those sky-high heels while keeping in mind that the opposite rings true for party pumps — the simpler, the better.
A festive ballet flat for your holiday wardrobe are these allover crystal slip ons from Leoffler Randall. With an elastic bridge strap and tiny bow detail, feel light and comfortable in shoes that you can sparkle all night in.
A favorite shoe of the Cut team this year was Sam Edelman’s popular slingback. If you love the comfort of flats but want a bit of height, consider these best sellers that come a wide range of colors and textures, but we love the metallic for an added holiday pop.
If Dorthy was a fashion girlie, these would be here special ruby-red slippers. For those who like a classic stiletto or just love the idea of wearing tinsel on your feet, you’re sure to make a statement in these festive red pumps.
If you’re a fan of Tory Burch shoes, then you’re familiar with her best-selling pierced collection, featuring flats, mules, and now pumps. Designer with bold pumps features a curved heel along with the two-toned hardware at the soft-tip toe. The shoes also come in a brownish-red hue.
Here, we have another textured flat option, but this time made of fine silk. The holiday red flat features a contrasting grosgrain trim and an elongated square toe.
Look familiar? Whether you wear just the bow shoes, or pair the heels with the brand’s matching bow dress, you’ll certainly be cocktail ready with these pretty pleats.
Tip 4: Your Bag Should Be Teeny (If Not, Statement)
Bringing a “gargantuan bag” to a sophisticated soirée is a major faux pas. Just ask Succession’s Mathew Macfadyen a.k.a. Tom Wambsgans. Luckily we’re still living in the era of the mini bag — the best accessory for all your fancy occasions. While clutches remain the default accessory of choice, thetiny-bag trend has spawned a wealth of options from silk pouches to structured miniature purses and embellished top handle bags. If you want to go a little larger (let’s say a step up from mini so you can fit more than one lipgloss and your phone), make sure to keep it elegant, dainty, and of course, statement.
If you are going for an all burgundy look for your holiday soirée, you might as well top it off with a cutesy burgundy bag. A part from the dainty top handle design, we love the little crystal bows which act as sparkling accessories for your accessory.
If you’re looking for a statement top handle bag that fits a lot of stuff (we’re talking phone, mini wallet, various makeup items, and even a pair of sunglasses), this small (but not super mini) metallic bag is exactly what you need.
This is the season of faux-fur and fleece, so it only makes sense to have a fluffy fuzzy bag, too. With its detachable strap, this crescent-shaped shearling bag can be both a tiny top handle for your cocktail look or an everyday crossbody.
This delicate drawstring chain bag comes in a range of colors and textures, but the eye-catching gold sequin is ideal for the season. Carry it on your shoulder or on your arm, this bag is a glittering addition to any cocktail fit.
A velvet bag to go with your velvet dress, perhaps? This Tory Burch mini flap purse, which features a quilted velvet design and embellished charms, is the party bag you’ll want to wear all season long.
Do you really need to spend a ton of money on a special events bag? Not really. Amazon has plenty of affordable options like this ornate black-and-gold rhinestone clutch.
Okay, we admit it. This isn’t a tiny bag. In fact it’s oversize. But this is the perfect accent accessory to jazz up a more simple cocktail look. We love the chocolate brown color (another popular hue for the season), and if you want to be a bit more festive, the bag also comes in a shiny silver.
Apart from shoes and a great handbag, your outfit is never complete without some jewelry. Necklaces are fine but earrings, given their placement, accentuate the face and help to fully balance a cocktail look, especially when there’s added sparkle involved. Whether you’re into standout geometric shapes, botanical-inspired clip-ons, or dangling rhinestone dusters, with these options, you won’t need much else to top off your outfit.
The artistic construction of the two-layered baubles is not only beautiful but functional with the top layer serving as the earring post and the larger bottom layer as the stopper.
In addition to flowers, shells have become another popular bauble design. But if you wan a more sculptural shell option, these standout sterling-silver clip-ons are sure to be a crowd-pleaser.
Add a bit of celestial flare to your look with these space inspired earrings. The plant-shape design, which features gold rings orbiting around a suspended glass pearl, is engineered as a stud to enable the perfect balance of movement and support.
If you’re a fan of Swarovski’s popular Millenia necklaces, then you’ll love these crystal drop earrings. Plus the tonal ice blue shades give total winter-wonderland vibes.
Take it from someone who owns these, these are the perfect party earring. They’re not too flashy, weight next to nothing, and the festive bow design manages to catch attention every time.
Chunky, geometric earnings are all the rage right now. And if you’re over the popular teardrop and heart shapes, try these vintage-inspired rectangle style studs.
Circling back to where it all began. Of course, you can never go wrong with a fabulous cocktail dress, especially a great little black number. But just because you choose black, doesn’t mean it has to be boring. There’s a wide range of elevated LBD styles out there, but to narrow down the madness, here’s a selection of trendy and black options that’ll make other guests wish they, too, went for a LBD.
For the bubble-hem lovers, here’s an option that is business on the top and party on the bottom. The stretchy, spandex-style bodice features a mockneck top with a puffy, mini skirt balloon bottom. The cheeky party mini also comes in red.
An elegant jacquard dress is a popular choice for the season, but instead of the typical red and gold, we love this dark-navy and black floral pattern dress from Ganni. The jacquard drop waist dress features a gathered skirt and dainty bow accents at the self-tie shoulder straps.
While this LBD appears to be a fairly simple long-sleeve midi, up close, the dress features a twisted bust detail, creating a subtle yet enchanting focal point. This is also a great option for a day-to-night look.
The fluffy tulle dress is not only glamorous — it’s fun! Moving in this dress is entertainment within itself. Wear the dress as is or style with a blazer or underneath an oversize sweater à la Carrie Bradshaw (the original lover of any kind of grand tulle moment).
In addition to sequins and fringe, did we mention that we also love feathers? Especially when they’re delicately done (and not too over the top) like this Rixo mini dress, which features a playful feathered bardot neckline and straps.
Staud has mastered the art of the mod mini — and this two-toned belle sleeve number is the perfect example. While the boat neck dress might feature a short skirt, the design features extra long, white flared-cuff sleeves, which add a trendy vibe to the otherwise timeless style.
By submitting your email, you agree to our
Terms and Privacy Notice
and to receive email correspondence from us. This site is protected by reCAPTCHA and the Google
Privacy Policy and
Terms of Service apply.
or
Already a subscriber?
What is your email?
This email will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
Password must be at least 8 characters and contain:
Lower case letters (a-z)
Upper case letters (A-Z)
Numbers (0-9)
Special Characters (!@#$%^&*)
This password will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
You’re in!
As part of your account, you’ll receive occasional updates and offers from New York, which you can opt out of anytime.
or
Already a subscriber?
What is your email?
This email will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
Password must be at least 8 characters and contain:
Lower case letters (a-z)
Upper case letters (A-Z)
Numbers (0-9)
Special Characters (!@#$%^&*)
This password will be used to sign into all New York sites. By submitting your email, you agree to our Terms and Privacy Policy and to receive email correspondence from us.
You’re in!
As part of your account, you’ll receive occasional updates and offers from New York, which you can opt out of anytime.
Already a subscriber?
Already a subscriber?
`;
// integrate Sub(x) scripts and elements
if (hostname !== 'subs.nymag.com') { // do not integrate on this subdomain
document.head.appendChild(trackingScript);
document.body.insertAdjacentHTML('beforeend', subXAnimationElements);
}
There was an error processing the request. Please try again later."}).catch(e=>console.error("Error verifying email: ",e)))(r.querySelector(".content"),o.bannerCTAVerification)})):(l.remove(),s.remove()),o.dismissable||n.remove(),o.useAlertIcon||a.remove(),r.classList.add("show"),n.addEventListener("click",()=>{u(),r.classList.remove("show")})}else r.remove()}});
}, {"1":1,"6":6,"12":12,"35":35,"40":40}];
window.modules["global-nav.client"] = [function(require,module,exports){"use strict";const dom=require(3),auth=require(12),signInButton=dom.find(".user-signin"),signOutButton=dom.find(".user-signout"),globalNav=dom.find('[class^="global-nav"]'),body=dom.find("body"),dropdownItems=dom.findAll(".dropdown-wrap"),gtm=require(1),appendLandingPageParams=require(136),pageUri=require(124).getPageUri(),subscriptionPromoLinks=dom.findAll(".persist-params"),searchString=window.location.search||"";function closeDropdowns(e){let n=globalNav.querySelectorAll(".dropdown.open");dropdownItems.forEach(function(t){let o=t.querySelector(".dropdown");!n||t.contains(e.target)&&27!==e.keyCode||o.classList.remove("open")})}function gtmSendReport(e,n,t){let o={eventCategory:"ecommerce",eventAction:"componentClick",brand:e,dimension23:"global-nav",list:pageUri,pageZone:"header",variant:"nav-link"};"global-nav-link"===t&&(o.eventLabel=n.href),gtm.reportNow(o)}function updateElementTargetUrlsIfQueryStrings(e){if(searchString){const n=new URLSearchParams(searchString);let t=e.href;if(t.includes("?")){const o=t.split("?"),i=new URLSearchParams(o[1]);for(let e of n.entries())i.set(e[0],e[1]);t=`${o[0]}?${i.toString()}`,e.href=t}else e.href=`${t}?${n.toString()}`}}function init(e){const n=e.querySelectorAll(".to-landing-page");window.addEventListener("auth:init",()=>{signInButton.addEventListener("click",function(e){e.preventDefault(),auth.showEmbeddedLoginFlow("top navigation")}),signOutButton.addEventListener("click",function(e){e.preventDefault(),gtmSendReport("Sign Out",e.target,"user-info-link"),auth.logout()}),auth.isAuthenticated()&&e.classList.add("signed-in"),auth.isSubscriber()&&e.classList.add("subscribed"),e.querySelectorAll(".user-link").forEach(e=>{e.classList.add("active")}),subscriptionPromoLinks.forEach(e=>{updateElementTargetUrlsIfQueryStrings(e)}),appendLandingPageParams(n)})}dropdownItems.forEach(function(e){e.addEventListener("click",function(){e.querySelector(".dropdown").classList.toggle("open")})}),body.addEventListener("click",closeDropdowns),document.addEventListener("keydown",closeDropdowns),globalNav.addEventListener("click",function(e){let n=e.target;n.classList.contains("global-nav-track")&>mSendReport(n.text,n,"global-nav-link")}),module.exports=init;
}, {"1":1,"3":3,"12":12,"124":124,"136":136}];
window.modules["aaa-module-mounting.legacy"] = [function(require,module,exports){"use strict";const _pickBy=require(221),_each=require(408),Fingerprint2=require(407),DS=require(406),Eventify=require(246);function registerGlobals(){window.DS=DS,window.Eventify=Eventify,window.Fingerprint2=Fingerprint2,DS.value("Eventify",Eventify),DS.value("Fingerprint2",Fingerprint2),DS.value("$document",window.document),DS.value("$window",window)}function mountDollarSliceComponents(){DS.service("components",["$document","$module",function(e,n){var o=_pickBy(n.definitions,e=>e.providerStrategy===n.providers.controller),r=Object.keys(o);function t(e){return o=>{try{n.get(e,o)}catch(e){logMountError(o,e)}}}_each(r,n=>{var o=e.querySelectorAll('[data-uri*="/_components/'+n+'/"]'),r=e.querySelectorAll('[data-uri$="/_components/'+n+'"]');_each(o,t(n)),_each(r,t(n))}),this.components=r}]),DS.get("components")}function logMountError(e,n){const o=e.outerHTML.slice(0,e.outerHTML.indexOf(e.innerHTML));console.error("Error attaching controller to "+o,n)}registerGlobals(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{mountDollarSliceComponents()}):mountDollarSliceComponents();
}, {"221":221,"246":246,"406":406,"407":407,"408":408}];
window.modules["ads.legacy"] = [function(require,module,exports){"use strict";const _map=require(118),_forEach=require(107),_isString=require(268),_intersectionWith=require(409),_isEqual=require(274),_each=require(408),_debounce=require(182),_sortBy=require(205),page=require(124),visit=require(114);DS.service("adService",["Eventify","$cid","$document","$window",function(e,t,a,i){var o,n,s,r,d,c,u,l,g={},p=this,h=[],f=visit.getQueryParamsObject(["utm_campaign"]),m=document.querySelector('script[data-type="ad-a9"]'),b=[],w=!1,v=[],y=document.querySelector('script[data-name="ad-doubleverify"]');document.querySelector('script[data-name="concert-ads"]')||(i.NYM={},i.NYM.analytics={},i.NYM.analytics.adStartTime=i.performance.now(),i.googletag=i.googletag||{},i.googletag.cmd=i.googletag.cmd||[],u=i.googletag,(m||y)&&(i.googletag.cmd=i.googletag.cmd||[],i.googletag.cmd.push(function(){i.googletag.pubads().disableInitialLoad()})),m&&(l=i.setInterval(function(){void 0!==window.apstag&&void 0!==window.apstag.timeout&&(i.clearInterval(l),window.apstag.cleared=!0,l=null)},10),setTimeout(function(){l&&(i.clearInterval(l),i.googletag.pubads().refresh(),window.apstag||console.log("MESSAGE: Timeout for A9 load exceeded, aborting"))},500)),y&&(b.push(new Promise(function(e){w?e():v.push(e)})),c=i.setTimeout(T,2500)),o=function(e){var t,a,o=e.data,n=[];return o.loaded?e:(o.loaded=!0,t=null,(t=o.sizes?u.defineSlot(o.name,o.sizes,o.id).addService(u.pubads()):u.defineOutOfPageSlot(o.name,o.id).addService(u.pubads())).setTargeting("adid",o.id),f.hasOwnProperty("utm_campaign")&&t.setTargeting("utmcamp",f.utm_campaign),a=p.getAdCount(o.label),t.setTargeting("label",o.label+"_"+o.site+"-"+a),u.display(o.id),u.pubads().addEventListener("slotOnload",function(){i.NYM.analytics.firstAdLoadTime||(i.NYM.analytics.firstAdLoadTime=i.performance.now(),i.NYM.analytics.firstAdLoadLabel=e.data.label)}),n=_(o),Promise.all(b).then(function(){n?window.apstag&&window.apstag.cleared?window.apstag.fetchBids({slots:[n],timeout:window.apstag.timeout},function(){u.cmd.push(function(){window.apstag.setDisplayBids(),u.pubads().refresh([t],{changeCorrelator:!1})})}):y&&u.pubads().refresh([t],{changeCorrelator:!1}):u.pubads().refresh([t],{changeCorrelator:!1})}),e.slot=t,e)},n=function(e){var a,i,o,n=t(),s=e.getAttribute("data-name"),r=e.getAttribute("data-sizes"),d=e.getAttribute("data-label"),c=e.getAttribute("data-site");n=e.id,r&&r.length?(r=r.split(","),a=[],_map(r,function(e){e=e.split("x"),i=parseInt(e[0]),o=parseInt(e[1]),a.push([i,o])})):(e.classList.add("oop"),a=!1),this.data={id:n,name:s,sizes:a,loaded:!1,label:d,site:c},g[n]=this},r=function(e){u.cmd.push(function(){var t=o(e);g[e.data.id]=t})},s=function(e){var t=[];e.slot?(t=_(e))&&window.apstag&&window.apstag.cleared&&window.apstag.fetchBids({slots:[t],timeout:window.apstag.timeout},function(){u.cmd.push(function(){window.apstag.setDisplayBids(),u.pubads().refresh([e.slot],{changeCorrelator:!1})})}):e&&r(e)},u.cmd.push(function(){var e,t,o,n=page.getMeta("article:tag"),s=page.getMeta("author"),r=i.location.href,d=(e=a.head.querySelector(".head-gtm"),t=a.body.querySelector(".gtm"),e&&"top"===e.getAttribute("data-gtm")?"gtmtop":t&&"bottom"===t.getAttribute("data-gtm")?"gtmbottom":"");o=[],_forEach([n,s,d],function(e){_forEach(e.split(","),function(e){(e=e.trim().toLowerCase().replace(/\s/g,"-").replace(/\'|\’/g,"")).length&&o.push(e)})}),u.pubads().setTargeting("kw",o),u.pubads().setTargeting("entry_group",o),r=r.slice(r.lastIndexOf("/")+1),u.pubads().setTargeting("pn",r),u.companionAds().setRefreshUnfilledSlots(!0),u.pubads().enableAsyncRendering(),u.enableServices()}),this.load=r,this.create=function(e){return new n(e)},this.refresh=function(e){var t;_isString(e)?(t=this.getById(e),s(t)):s(e)},this.remove=function(e){var t=e.data.id;a.getElementById(t).innerHTML=""},this.getAdCount=function(e){var t,a=0,i=Object.keys(g);return _each(i,function(i){(t=g[i]).data.loaded&&t.data.label===e&&a++}),a},this.getById=function(e){return g[e]},d=_debounce(function(){var e={TopLeaderboard:1,RightColTopMPU:2,outOfPage:99,"homepageTakeover/TopLeaderboard":1},t=_sortBy(h,function(t){return e[t.data.label]||10});_forEach(t,function(e){return e.data.sizes?r(e):i.setTimeout(function(){r(e)},2e3)}),y&&window.PQ.cmd.push(()=>{try{window.PQ.loadSignals(["ids","bsc","vlp"],T)}catch(e){T(),console.error(`There has been an error loading Double Verify signals: ${e}`)}}),h=[]},10),this.addToPageLoadQueue=function(e){h.push(e),d()});function _(e){var t,a=e.sizes;return a=_intersectionWith(a,[[970,250],[970,90],[728,90],[300,600],[300,250],[320,100],[320,50]],_isEqual),e.sizes&&e.sizes.length&&(t={slotID:e.id,sizes:a,slotName:e.label}),t}function T(){i.clearTimeout(c),w=!0,_forEach(v,function(e){e()})}}]);
}, {"107":107,"114":114,"118":118,"124":124,"182":182,"205":205,"268":268,"274":274,"408":408,"409":409}];
window.modules["cid.legacy"] = [function(require,module,exports){"use strict";DS.service("$cid",function(){var r=Math.floor(100*Math.random());return function(){return"cid-"+ ++r}});
}, {}];
window.modules["client.legacy"] = [function(require,module,exports){"use strict";require("cid.legacy"),require("ads.legacy"),require("facebook.legacy"),require("aaa-module-mounting.legacy");
}, {"cid.legacy":"cid.legacy","aaa-module-mounting.legacy":"aaa-module-mounting.legacy","ads.legacy":"ads.legacy","facebook.legacy":"facebook.legacy"}];
window.modules["facebook.legacy"] = [function(require,module,exports){"use strict";DS.service("facebook",[function(){this.fb=function(i){window.FB&&window.FB[i].apply(this,Array.prototype.slice.call(arguments,1))}}]);
}, {}];
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o typeof key === 'string' && key.match(/\.legacy$/)).forEach(key => window.require(key));
}
function tryToMount(fn, el, name) {
try {
fn(el); // init the controller
} catch (e) {
const elementTag = el.outerHTML.slice(0, el.outerHTML.indexOf(el.innerHTML));
console.error(`Error initializing controller for "${name}" on "${elementTag}"`, e);
}
}
/**
* mount client.js component controllers
*/
function mountComponentModules() {
Object.keys(window.modules).filter(key => typeof key === 'string' && key.match(/\.client$/)).forEach(key => {
let controllerFn = window.require(key);
if (typeof controllerFn === 'function') {
const name = key.replace('.client', ''),
instancesSelector = `[data-uri*="_components/${name}/"]`,
defaultSelector = `[data-uri$="_components${name}"]`,
instances = document.querySelectorAll(instancesSelector),
defaults = document.querySelectorAll(defaultSelector);
for (let el of instances) {
tryToMount(controllerFn, el, name);
}
for (let el of defaults) {
tryToMount(controllerFn, el, name);
}
}
});
}
// Make sure that a `window.process.env.NODE_ENV` is available in the client for any dependencies,
// services, or components that could require it
// note: the `` value is swapped for the actual environment variable in /lib/cmd/compile/scripts.js
window.process = window.process || {};
window.process.env = window.process.env || {};
if (!window.process.env.NODE_ENV) {
window.process.env.NODE_ENV = '';
}
// note: legacy controllers that require legacy services (e.g. dollar-slice) must
// wait for DOMContentLoaded to initialize themselves, as the files themselves must be mounted first
mountLegacyServices();
mountComponentModules();
// ]]