Belle-Ve Bricks

Custom Creations,
Unforgettable Impressions.

Building Brand Awareness Brick by Brick: Unleashing the Power of LEGO® Sets

Trusted by Over 392 Distinctive Clients
Custom model
Bring Your Idea to Life

In today’s fiercely competitive market, establishing and maintaining brand awareness is essential for the success of any business. As marketing strategies continue to evolve in the 21st century, companies are constantly seeking innovative ways to capture the attention of their target audience and make a lasting impression. One powerful tool that has proven highly effective as promotional gifts. 

Among the vast array of options available, LEGO® sets stand out as an excellent choice. With their universal appeal, association with creativity and innovation, high perceived value, and ability to encourage social sharing, LEGO® sets offer a unique opportunity to enhance brand awareness and forge a strong connection with consumers. 

In this article, we will delve into the significance of brand awareness in today’s marketing industry, explore the importance of branding for business development, highlight the role of promotional gifts in brand awareness, and examine why LEGO® sets are the ultimate promotional gifts. 

So, fasten your seatbelts and get ready to discover the power of LEGO® sets in building effective brand awareness campaigns.

What is Brand Awareness?

Brand awareness refers to the extent to which consumers are familiar with the distinctive qualities or image of a particular product or brand. It’s when consumers recognize or recall a brand through its attributes, such as the logo, jingle, packaging, or associations with a particular lifestyle or quality. High brand awareness means that the brand is well-established in the market and readily comes to consumers’ minds when they think of a specific product category or need.

The evolution of marketing strategies in the 21st century

As we traverse the 21st century, marketing strategies have evolved rapidly, especially with the advent and proliferation of the internet and social media.

1. Digital Revolution

In the early 2000s, marketing was largely centered around traditional channels such as television, radio, and print. However, the digital revolution brought with it new avenues for marketers. These included websites, social media, email, and mobile apps.

2. Social Media and Influencer Marketing

The rise of social media platforms like Facebook, Instagram, and Twitter gave birth to influencer marketing. Brands began collaborating with individuals with a large following on these platforms to promote their products.

3. Data-Driven Marketing

Advancements in data analytics have enabled marketers to understand their customers better. They can use customer data to personalize marketing content and target specific demographics.

4. Content Marketing

The 21st century has seen the rise of content marketing, where brands create valuable, relevant, and consistent content to attract and retain a clearly defined audience.

5. Omni-Channel Marketing

This involves integrating different marketing channels and customer touchpoints to create a seamless customer experience, regardless of the customer’s platform or device.

6. Sustainable and Ethical Marketing

More recently, consumers have been paying close attention to the environmental and ethical practices of companies. Brands now include sustainability and ethical practices as part of their marketing strategies.

The importance of promotional gifts in modern marketing

Promotional gifts have become an integral part of modern marketing for several reasons:

1. Building Relationships

Giving gifts to customers or partners can help in building and strengthening relationships. It shows that the brand values them, which can lead to increased loyalty and advocacy.

2. Brand Recognition

Promotional gifts, especially those used daily, keep the brand at the forefront of the consumer’s mind. When the consumer or those around them see the branded item, it reinforces brand awareness.

3. Cost-effective Marketing

Compared to some advertising methods, promotional gifts are a cost-effective way to market a product or service, as they remain in use for longer.

4. Enhancing Brand Image

Thoughtful and high-quality promotional gifts can enhance the brand’s image, making it appear more professional, reliable, and committed to customer satisfaction.

5. Generating Leads

Promotional gifts can also be used to generate leads. Giving a gift to one person can spark interest among others who see it, leading them to inquire about the brand.

The Importance of Brand Awareness in Today’s Marketing Industry

1. Establishing Trust Among Consumers

One of the fundamental reasons brand awareness is important in today’s marketing industry is that it helps in establishing trust among consumers. When consumers are familiar with a brand, they are more likely to trust its products or services. Consistent brand messaging and positive interactions with a brand build a sense of reliability and dependability. In an era where consumers are bombarded with countless options, trust becomes a key factor in their decision-making process.

2. Distinguishing a Brand from Competitors

In a highly saturated market, it is crucial for a brand to stand out from its competitors. Brand awareness helps in distinguishing a brand by highlighting its unique features, values, and qualities. Through creative branding elements such as logos, taglines, and brand stories, a company can create a distinct image in the minds of consumers. This distinction becomes part of the brand’s identity and sets it apart from others, making it the preferred choice among alternatives.

3. Encouraging Customer Loyalty and Retention

Brand awareness is not just about attracting new customers; it’s also about retaining existing ones. Customers are more likely to remain loyal When they are aware of and resonate with a brand’s values and offerings. This loyalty often translates into repeat purchases and brand advocacy. Engaging with customers through social media, loyalty programs, and personalized content are some of the ways brands can leverage awareness to foster loyalty and retention.

4. Enhancing Credibility and Perceived Value

A well-known brand is often perceived as more credible and valuable than its lesser-known counterparts. This is because consumers tend to associate brand awareness with quality and experience. For instance, a customer is likely to attribute higher value to a product from a recognizable brand compared to a similar product from an unknown brand. This enhanced credibility and perceived value allow the brand to command premium pricing and build a more prestigious image.

5. Facilitating Word-of-Mouth Marketing

Brand awareness plays a significant role in facilitating word-of-mouth marketing. When consumers have a positive experience with a brand they are familiar with, they are more likely to share this experience with friends, family, and on social media platforms. This kind of organic sharing is invaluable, as recommendations from friends or family members are often considered more trustworthy than traditional advertising. Moreover, in the age of social media, a single share can quickly reach hundreds or thousands of potential customers, amplifying the brand’s reach exponentially.

The Significance of Branding in Business Development

1. Building a Corporate Identity

Definition

Corporate identity refers to the way a corporation presents itself to the public and is perceived by its audience. It encompasses various elements, including the company’s name, logo, design, and communication style.

Importance

Building a strong corporate identity through branding is crucial because it creates a consistent and memorable image for the business. This image becomes synonymous with the company’s values, culture, and offerings. A well-crafted corporate identity helps to create a sense of belonging among employees and serves as a foundation for all communication and marketing efforts.

2. Influencing Consumer Perception

Perception Management

Consumer perception is the way consumers view a brand and interpret its messages. Effective branding can be used to positively shape these perceptions.

Techniques

Through storytelling, visual elements, and targeted communication, branding can create perceptions of quality, reliability, innovation, or any other attribute the business wants to be associated with.

Long-term Impact

Over time, these perceptions can strongly influence consumer behavior and preferences, making them more likely to choose the brand over competitors.

3. Strengthening Customer Relationships

Emotional Connection

Branding helps in creating an emotional connection with customers. By consistently communicating brand values and purpose, customers are likely to develop a sense of attachment to the brand.

Trust and Loyalty

Effective branding builds trust. Customers who trust a brand are more likely to remain loyal, even when other options are available.

Personalized Experience

Customized branding elements, such as personalized emails, offers, and services, help give customers a unique experience, further strengthening relationships.

4. Attracting Potential Investors and Partnerships

Confidence in the Brand

A strong brand can attract customers, investors, and business partners. A coherent and positive brand image can instill confidence in potential investors and partners.

Expansion and Growth

Having a reputable brand makes collaborations and partnerships easier. Other companies and investors are more likely to get involved if they believe that the association with your brand will be mutually beneficial.

Market Position

For investors, a strong brand represents a commanding market position and suggests potential profitability, making the business an attractive investment opportunity.

5. Guiding Product Development and Innovation

Reflecting Customer Needs

Branding rooted in understanding customer needs and preferences can guide product development efforts. It ensures that the products or services developed align with what the customers expect from the brand.

Staying Relevant

As markets evolve, so do customer expectations. Strong branding keeps a business attuned to changes in consumer preferences, helping them innovate accordingly.

Encouraging Feedback

An approachable brand encourages customer feedback, which is invaluable in product development. It offers insights that can be used to improve existing products or develop new ones that meet emerging demands.

The Role of Promotional Gifts in Brand Awareness

1. Creating a Tangible Connection with the Audience

Personal Touch

Promotional gifts add a personal touch to a brand’s interaction with its audience. Unlike digital advertisements or social media posts, physical gifts are tangible items consumers can use and interact with.

Physical Presence

By having a physical item such as a branded pen, notebook, or mug, the brand maintains a presence in the consumer’s daily life, creating a continuous and tangible connection.

Memorable Interaction

Receiving a gift is often associated with positive emotions. These positive emotions can be transferred to the brand, making the interaction more memorable and impactful.

2. Generating Buzz and Interest in the Brand

Conversational Piece

Unique or valuable promotional gifts can become a topic of conversation among recipients and their social circles, generating buzz around the brand.

Social Media Sharing

Recipients of promotional gifts may share pictures or mention the brand on social media, increasing exposure and leading to an organic interest in the brand.

Events and Launches

Promotional gifts can be particularly effective during events, product launches, or campaigns, where they can create an immediate buzz and attract attention to the brand.

3. Encouraging Brand Recall

Daily Use Products

Items that can be used regularly, such as pens or tote bags, keep the brand in sight and mind, encouraging recipients to remember and think of the brand more often.

Association

A well-thought-out promotional gift can be associated with the brand’s products or values, reinforcing the brand’s identity every time the item is used.

Recognition

Branded gifts that carry the company’s logo or tagline help improve brand recognition and, if used in environments where purchase decisions are made.

4. Showcasing Company Values and Culture

Alignment with Brand Values

Selecting promotional gifts that align with the brand’s values can communicate what the company stands for. For example, a company that values sustainability might choose eco-friendly products.

Culture Representation

Gifts that reflect the company’s culture can create a connection with like-minded consumers. For instance, a tech company could give away innovative gadgets or accessories.

Building Image

Thoughtfully selected promotional gifts can enhance the company’s image as being generous, innovative, customer-centric, or having other desirable attributes.

5. Providing Value to the Consumer

Utility

Promotional gifts that offer practical utility are more likely to be appreciated by recipients. This appreciation can translate into a positive perception of the brand.

Exclusive Benefits

Gifts that provide exclusive benefits, such as access to special offers or content, can make consumers feel valued and privileged.

Longevity

Quality gifts that last a long time can continuously provide value to the consumer, positively affecting their perception and relationship with the brand.

Why LEGO® Sets are the Best Promotional Gifts

1. Universal Appeal Across Age Groups

Timeless Popularity

LEGO® sets have remained popular for decades, appealing to children and adults. Their timeless design and the endless possibilities they offer in the building make them a favorite across generations.

Broad Demographic Reach

By choosing LEGO® sets as promotional gifts, brands can reach a wide demographic, as people of various ages, backgrounds, and interests cherish these sets.

Positive Nostalgia

For many adults, LEGO® sets can evoke a sense of nostalgia, reminding them of their childhood. This positive emotional connection can be associated with the brand giving the gift.

2. Association with Creativity and Innovation

Creative Expression

LEGO® sets are synonymous with creativity, allowing individuals to build and create structures and designs using their imagination.

Innovative Thinking

The process of building with LEGO® encourages problem-solving and innovative thinking. Associating a brand with these qualities can enhance its image as a creative and innovative entity.

Learning and Development

Especially for children, LEGO® sets are not just toys but also educational tools that can aid in learning and development. A brand giving LEGO® as a gift can be seen as contributing to education.

3. High Perceived Value

Quality and Durability

LEGO® is known for its high-quality and durable products. Giving a LEGO® set as a promotional gift reflects that the brand is willing to give something of value.

Brand Prestige

LEGO® as a brand carries its prestige. Associating with LEGO® through promotional gifts can lend some of this prestige to the giving brand.

Memorable Experience

Building a LEGO® set is an experience in itself. By providing a memorable experience, the brand ensures that it is remembered positively.

4. Encouraging Social Sharing and Virality

Shareable Content

People often take pride in their LEGO® creations and are likely to share pictures and videos on social media, which can inadvertently promote the brand that gave the set.

Online Communities

There are numerous online communities and forums dedicated to LEGO® enthusiasts. Being featured or mentioned in these communities can increase brand visibility among a highly engaged audience.

Viral Challenges

Brands can create challenges or contests around the LEGO® sets they distribute as promotional gifts, encouraging recipients to build something specific and share it online for rewards.

5. Customizability for Branding Purposes

Branded Sets

LEGO® offers the option to create custom sets or pieces with a company’s branding, logo, or other identifying marks.

Themed Sets

Depending on the brand’s industry or message, themed LEGO® sets can be chosen or designed to align with the brand image.

Instruction Booklets and Packaging

Brands can customize instruction booklets and packaging with their branding, messages, or promotions, adding another layer of personalization.

Types of LEGO® Sets That Can Be Used as Promotional Gifts

1. Custom Branded LEGO® Sets Reflecting Company Products or Logos

Product Replicas

Companies can collaborate with LEGO® to create custom sets that are miniature replicas of their products. For example, an automobile company can create LEGO® sets of their cars.

Logo Builds

Custom sets can be designed to build the company’s logo. These sets can be used as desktop display pieces, serving as a constant reminder of the brand.

Building Bricks with Logo

Regular LEGO® bricks can be imprinted with the company’s logo to construct a structure using branded pieces whenever a system is built.

2. Themed Sets that Align with the Company’s Industry or Interests

Industry-Related Themes

For instance, a space research organization can use space-themed LEGO® sets, while a construction company can opt for architectural building sets.

Celebratory Themes

Companies can choose sets that align with certain celebrations or events, like holiday-themed sets during the festive season.

Educational Themes

For brands focusing on education or child development, educational-themed sets such as LEGO® Technic or LEGO® Science sets can be an ideal choice.

3. LEGO® Gift Cards for Customers to Choose Their Own Sets

Freedom of Choice

Providing LEGO® gift cards as promotional gifts allows recipients to choose their own sets according to their interests.

Engaging with the Brand

As recipients browse options, they actively engage with the LEGO® brand and, by association, the company that gifted them the card.

Hassle-Free Distribution

Gift cards are easy to distribute, making them convenient for companies, especially for online promotions or events.

4. Collaborative Sets Involving Partnerships with Other Brands or Franchises

Cross-Promotion

Companies can partner with LEGO® and another brand or franchise to create collaborative sets. This can be particularly effective for movie or game releases.

Exclusive Collaborative Sets

Creating an exclusive collaborative set can generate buzz, as fans of both brands may be keen to get their hands on a limited-edition product.

Building a Community

Such collaborations can build a community of followers who are enthusiasts of both the brands involved, resulting in mutual benefits.

5. Limited Edition or Collector’s Sets for High-Value Clients or Partners

Exclusivity

Limited edition or collector’s sets are often sought after by LEGO® enthusiasts. Gifting these sets to high-value clients or partners can make them feel valued and exclusive.

Investment Perception

These sets are often perceived as investments as they may appreciate value over time. This reflects the brand’s thoughtfulness in providing a gift with potential financial value.

Strengthening Relationships

Gifting collector’s sets can strengthen business relationships, as it reflects the brand’s willingness to go the extra mile to appreciate and value its clients or partners.

Implementing LEGO® Sets in Your Promotional Strategy

1. Identifying the Target Audience

Market Segmentation

Analyze your market and segment it into groups based on demographics, interests, or behaviors. This will help understand which segment will most likely appreciate and engage with LEGO® sets.

Understanding Customer Interests

Gather insights on your target audience’s interests, hobbies, and preferences. This will help in selecting LEGO® sets that resonate with them.

Tailoring to the Audience

Tailor the promotional campaign to the specific audience segment you are targeting with the LEGO® sets.

2. Selecting Appropriate LEGO® Sets

Align with Brand Image

Choose LEGO® sets that are in line with your brand image and values. For example, if you are a tech company, you might opt for sets that promote innovation and creativity.

Consider the Occasion

If the LEGO® sets are being used for a specific event or celebration, choose sets that are themed appropriately.

Budget Constraints

Keep the budget in mind while selecting the sets. It’s crucial to balance the perceived value of the gift with the cost to the company.

3. Creating Branding Materials and Packaging

Custom Packaging

Work with LEGO® to create custom packaging incorporating your brand logo, colors, and messaging. This enhances the connection between the gift and your brand.

Instruction Manuals

Include branded instruction manuals with additional information about your company and how the LEGO® sets relate to your products or services.

Special Messages

Include a personalized thank-you note or message in the packaging to add a personal touch to the promotional gift.

4. Integrating with Other Marketing Channels

Social Media Engagement

Encourage recipients to share their creations on social media and tag your brand. Create hashtags specific to the campaign for tracking.

Email Marketing

Send emails to your customer base announcing the promotional campaign, and follow up with recipients to get feedback on the LEGO® sets.

Events and Trade Shows

Use the LEGO® sets as giveaways at events and trade shows and integrate them into presentations or displays to create a cohesive marketing experience.

5. Measuring the Impact on Brand Awareness

Social Media Analytic

 Monitor the number of mentions, shares, and hashtags related to the promotional campaign on social media to gauge its reach and engagement.

Surveys and Feedback

Send out surveys to recipients to gather feedback on the promotional gifts and understand how they impacted their perception of your brand.

Sales and Customer Acquisition

Analyze sales data and customer acquisition rates during and after the campaign to see if there is a positive correlation with the LEGO® promotional campaign.

Case Studies

Examples of Successful LEGO® Promotional Campaigns

LEGO® and Shell Partnership:

Background: In the early 1990s and later in 2012, LEGO® partnered with Shell to produce a series of Shell-branded LEGO® sets. The sets included Shell gas stations, vehicles, and minifigures.

Success: The partnership was mutually beneficial as it combined both brands’ prestige and global reach. It also helped Shell in brand exposure among the younger generation.

LEGO® and Starbucks Holiday Campaign:

Background: During the holiday season, LEGO® collaborated with Starbucks for a promotional campaign where Starbucks stores offered limited-edition holiday-themed LEGO® sets.

Success: The campaign drove foot traffic to Starbucks stores during the holiday season and created a buzz on social media as customers shared their LEGO® creations.

LEGO® Mini-Figures in the Mail Campaign:

Background: A campaign by a digital marketing company involved sending out LEGO® mini-figures to prospective clients along with a personalized message asking for a meeting.

Success: The campaign reported an 80% response rate, with many clients appreciating the creativity and uniqueness of the campaign.

Lessons Learned from These Campaigns

Brand Synergy

The LEGO® and Shell partnership showcased that collaboration between two brands can create synergy and extend the reach and impact of the campaign.

Seasonal Promotions

The LEGO® and Starbucks campaign highlighted the effectiveness of using seasonal themes and exclusivity to drive customer engagement during specific periods.

Creativity and Personalization,

The mini-figures in the mail campaign demonstrated the importance of creativity and personalization in capturing the target audience’s attention.

Insights on How to Improve Future Promotional Strategies

Customization and Personalization

Companies should focus on creating customized and personalized LEGO® sets that resonate with their brand image and the target audience’s interests.

Cross-Channel Integration

Integrate the promotional campaign across multiple channels to maximize reach and engagement, including social media, email, and in-store promotions.

Data Analysis

Utilize data analytics to understand the preferences and behaviors of the target audience and use these insights to refine the promotional strategy.

Measuring ROI

Includes mechanisms for tracking and measuring the campaign’s return on investment (ROI). This can help in understanding the effectiveness and informing future campaign strategies.

Sustainability

With growing consumer consciousness towards sustainability, brands can explore options for environmentally-friendly packaging and materials in collaboration with LEGO®.

Conclusion

Brand awareness plays a crucial role in today’s competitive marketing industry. It establishes consumer trust, distinguishes a brand from competitors, encourages customer loyalty and retention, enhances credibility and perceived value, and facilitates word-of-mouth marketing. Promotional gifts, in particular, are practical tools for building brand awareness. They create a tangible connection with the audience, generate buzz and interest in the brand, encourage brand recall, showcase company values and culture, and provide value to the consumer.

Final Thoughts on Why LEGO® Sets are an Effective Choice for Promotional Gifts

LEGO® sets stand out as one of the best options for promotional gifts due to their universal appeal across age groups, association with creativity and innovation, high perceived value, ability to encourage social sharing and virality, and customizability for branding purposes. Their timeless popularity, positive emotional connections, and opportunities for customization make them powerful tools for enhancing brand awareness and leaving a lasting impression on recipients.

In today’s dynamic marketing landscape, it is essential for brands to continuously innovate and find unique ways to engage with their target audience. Promotional gifts, such as custom LEGO® sets, provide an excellent opportunity to create memorable experiences and strengthen brand awareness. By understanding your target audience, selecting appropriate sets, creating branded materials, integrating with other marketing channels, and measuring the impact, you can develop effective promotional strategies that resonate with your customers.

Call Belle-Ve Bricks for Custom LEGO® Sets:

Are you looking to create a memorable and impactful promotional campaign? Belle-Ve Bricks is here to help! Our team of experts specializes in creating custom LEGO® sets that reflect your brand’s identity and values. Whether you need product replicas, branded or themed sets, we can tailor our offerings to meet your specific needs. Let us help you engage your target audience, drive brand awareness, and leave a lasting impression. Visit our website or contact us today to discuss your promotional goals and start designing your unique custom LEGO® sets. Take your promotional strategy to new heights with Belle-Ve Bricks!

<div class="badge-base LI-profile-badge" data-locale="en_US" data-size="large" data-theme="dark" data-type="HORIZONTAL" data-vanity="ferdi-vol" data-version="v1"><a class="badge-base__link LI-simple-link" href="https://www.linkedin.com/in/%E2%9C%85-ferdi-vol-corporate-gifts/?trk=profile-badge"></a></div>
/* Auto generated, hash = 5dceu9kevqjdyuy2uw1atqrsu */
//TODO: Break this file down so that we can actually unit test it.
(function(window) {
  /**
  * Renders all unrendred LinkedIn Badges on the page
  */
  window.LIRenderAll = function () {
    var CALLBACK_NAME     = 'LIBadgeCallback', //Must match callback on helpers.js
        BADGE_NAMES       = '.LI-profile-badge, .LI-entity-badge',
        // TODO -- tracking param for other badge types
        TRACKING_PARAM    = 'profile-badge',
        responsesReceived = 0, //Keeps track of number of responses recieved for proper cleanup when finished
        expectedResponses = 0, //Keeps track of number of responses to expect
        scripts           = [ ], //Keeps track of scripts added for proper cleanup when finished
        childScripts      = {}, //Keeps track of child scripts to render
        badges            = Array.prototype.slice.call(document.querySelectorAll(BADGE_NAMES));

    var i, len, badge, rendered;
    for (i = 0, len = badges.length;  i < len; i++) {
      badge    = badges[i];
      rendered =  badge.getAttribute('data-rendered');
      if (!rendered) {
        expectedResponses++;
        badge.setAttribute('data-rendered', true);
        renderBadge(badge);
      }
    }

    function isCNDomain() {
      if (typeof window !== "undefined") {
        var hostName = window.location && window.location.hostname ||  '';
        return (/linkedin(-ei)?.cn$/).test(hostName);
      }

      return false;
    }

    function generateUrl(isEI) {
      var domainPrefix = isEI ? 'https://badges.linkedin-ei' : 'https://badges.linkedin';
      if (isCNDomain()) {
        return domainPrefix + ".cn/";
      }

      return domainPrefix + ".com/";
    }

    function getBadgeKeyQueryParams(badge) {
      return Array.prototype.slice.call(badge.attributes).filter(function (attr) {
        return attr.name.lastIndexOf('data-key-', 0) !== -1;
      }).map(function (attr) {
        // Most browsers automatically lowercase the attribute name when its being read
        // We are calling lowercase on it again to ensure consistency for any browsers that are lagging behind.
        return encodeURIComponent(attr.name.replace('data-', '').toLowerCase()) + '=' + encodeURIComponent(attr.value);
      });
    }

    /*
    * Renders a single badge on the page
    * @param badge: div element of badge to render
    */
    function renderBadge(badge) {
      var size       = badge.getAttribute('data-size'),
          locale     = badge.getAttribute('data-locale'),
          type       = badge.getAttribute('data-type'),
          theme      = badge.getAttribute('data-theme'),
          vanity     = badge.getAttribute('data-vanity'),
          version    = badge.getAttribute('data-version'),
          isEI       = badge.hasAttribute('data-ei'),
          entity     = badge.getAttribute('data-entity'),
          isCreatePage = badge.hasAttribute('data-iscreate'),
          uid        = Math.round(1000000 * Math.random()),
          baseUrl = generateUrl(isEI),
          queryParams = [
            'locale=' + encodeURIComponent(locale),
            'badgetype=' + encodeURIComponent(type),
            'badgetheme=' + encodeURIComponent(theme),
            'uid=' + encodeURIComponent(uid),
            'version=' + encodeURIComponent(version)
          ],
          url;

      if (version === 'v2') {
        baseUrl += 'view';
        queryParams.push('badgesize=' + encodeURIComponent(size));
        queryParams.push('entity=' + encodeURIComponent(entity));
        queryParams = queryParams.concat(getBadgeKeyQueryParams(badge));
      } else {
        baseUrl += 'profile';
        queryParams.push('maxsize=' + encodeURIComponent(size));
        queryParams.push('trk=' + encodeURIComponent(TRACKING_PARAM));
        queryParams.push('vanityname=' + encodeURIComponent(vanity));
      }

      if (isCreatePage) {
        queryParams.push('fromCreate=true');
      }

      url = baseUrl + '?' + queryParams.join('&');
      badge.setAttribute('data-uid' , uid);
      jsonp(url); //Calls responseHandler when done
    }

    /**
    * Handles a response from the server. Finds badge matching badgeUid and inserts badgeHtml there
    * @param badgeHtml: String representing contents of the badge
    * @param badgeUid: UID of the badge to target
    **/
    function responseHandler(badgeHtml, badgeUid) {
      responsesReceived ++;

      var i, badge, uid, isCreate;
      var defaultWidth = 330 // max possible width
      var defaultHeight = 300 // max possible height

      for (i = 0, len = badges.length; i < len; i++) {
        badge = badges[i];
        // isCreate needed to prevent reloading artdeco script tag
        isCreate = badge.getAttribute('data-iscreate');
        uid   = parseInt(badge.getAttribute('data-uid'), 10);
        if (uid === badgeUid) {
          var badgeMarkup = `<body>${badgeHtml}</body>`
          var iframe = document.createElement('iframe');
          iframe.onload = function() {
            var iframeBody = iframe.contentWindow.document.body;
            // 5 px buffer to avoid the badge border being cut off.
            iframe.setAttribute('height', (iframeBody.scrollHeight || defaultHeight) + 5);
            iframe.setAttribute('width', (iframeBody.scrollWidth || defaultWidth) + 5);
          };
          iframe.setAttribute('frameBorder', '0');
          iframe.style.display = 'block';
          badge.appendChild(iframe);
          iframe.contentWindow.document.open();
          iframe.contentWindow.document.write(badgeMarkup);
          iframe.contentWindow.document.close();
          replaceScriptTags(badge, isCreate);
        }
      }
      tryClean();
    }

  // These functions are needed because badge markup is added via innerHtml property which does not run script tags
  function replaceScriptTags(node, isCreate) {
    if (shouldReplaceNode(node, isCreate)) {
      node.parentNode.replaceChild(cloneScriptNode(node), node);
      childScripts[node.src] = true;
    } else {
      var i = 0,
          children = node.childNodes;
      while (i < children.length) {
        replaceScriptTags(children[i++], isCreate);
      }
    }
    return node;
  }

  function shouldReplaceNode(node, isCreate) {
    return isScriptNode(node) && !childScripts[node.src] && (!isCreate || (isCreate && !node.getAttribute('data-isartdeco')));
  }

  function isScriptNode(node) {
    return node.tagName === 'SCRIPT';
  }

  function cloneScriptNode(node){
    var script  = document.createElement("script");
    for( var i = node.attributes.length-1; i >= 0; i-- ) {
      script.setAttribute( node.attributes[i].name, node.attributes[i].value );
    }
    return script;
  }

    // Gets all incoming responses
    window[CALLBACK_NAME] = responseHandler;

    /**
    * Tries to clean added tags
    **/
    function tryClean() {
      //Clean up after all requests are done..
      //Accounts for people including script more than once
      var done = (responsesReceived >= expectedResponses && expectedResponses > 0) || responsesReceived >= badges.length;
      if (done) {
        delete window[CALLBACK_NAME];

        // remove all script tags
        scripts.map(function(script){
          document.body.removeChild(script);
        });

      }
    }

    /*
    * Makes Jsonp request, responses handles by CALLBACK_NAME
    * @param url String: url of server to make request to
    */
    function jsonp(url) {
      var script = document.createElement('script');
      script.src = url;
      scripts.push(script);
      document.body.appendChild(script);
    }
  };

  if (document.readyState === 'complete') {
    window.LIRenderAll();
  } else {
    window.addEventListener('load', window.LIRenderAll, false);
  }

})(window);
Popular Posts