Belle-Ve Bricks

Building Brands, Brick by Brick.

How LEGO® Stands Up to Other Toys: A Comparative Analysis

Create Your

We help you from start to finish to create and deliver your tailor-made custom model.
Custom model
Continue

The story of LEGO®, one of the most iconic toy brands globally, began in 1932 in the small Danish town of Billund. Originally, LEGO® was a small carpentry workshop run by Ole Kirk Christiansen, making stepladders, ironing boards, and wooden toys. The name “LEGO” was coined from two Danish words ‘leg’ and ‘godt’, which translates to “play well.”

The shift towards the production of plastic toys started in 1947, but it was not until 1958 that the now-iconic LEGO® brick with its unique interlocking principle was patented, laying the foundation for one of the most versatile and innovative toys in history.

Since then, LEGO® has consistently expanded its offerings with various themed sets, partnerships with movie franchises, and the introduction of interactive elements, such as programmable robotics sets. The brand’s appeal transcends age and geography, with sets designed for various age groups and themes that cater to diverse interests.

LEGO® as One of the Most Renowned Toys in the World

Today, LEGO® stands tall as one of the most renowned and universally loved toys in the world. Their iconic bricks are instantly recognizable and have sparked countless hours of creative play in children and adults alike.

LEGO®’s impact on the toy industry and popular culture at large is undeniable. From humble beginnings, it has grown into a multibillion-dollar global enterprise, with its products sold in more than 140 countries.

In a testament to its cultural impact, the LEGO® brick was inducted into the Toy Hall of Fame in 1998. Furthermore, a 2021 study by the Reputation Institute declared LEGO® to be the most reputable company globally, a distinction based on factors like product quality, innovation, and corporate social responsibility. In 2022 LEGO® even made over 9 billion dollars according to Toy Statistics.

Beyond toys, LEGO® has also made its mark in video games, movies, and TV shows, further broadening its reach and reinforcing its status as an iconic brand that encourages creativity, problem-solving, and endless fun.

Notable Achievements of LEGO®

LEGO®’s journey from a small carpenter’s workshop in Denmark to one of the most recognized brands worldwide is marked with numerous achievements and awards.

Significant Awards Won by LEGO®

Toy of the Century: In 2000, both Fortune Magazine and the British Association of Toy Retailers bestowed the prestigious “Toy of the Century” title on the LEGO® brick, a recognition of its enduring popularity and impact.

National Toy Hall of Fame: In 1998, the LEGO® brick was inducted into the National Toy Hall of Fame, further attesting to its status as a timeless, universally beloved toy.

“Toy of the Year” Awards: LEGO® has won several awards from The Toy Association, including the coveted “Toy of the Year” award in multiple categories over the years. Notably, LEGO® Star Wars: The Child set won the Specialty Toy of the Year in 2021.

Most Powerful Brand in the World: In 2017, LEGO® was named the world’s most powerful brand by Brand Finance, surpassing even global giants such as Google and Ferrari.

The Global Impact and Recognition of LEGO®

The global impact of LEGO® extends far beyond its impressive array of awards. As a brand, LEGO® has continuously contributed to the development of children’s creativity, motor skills, and problem-solving abilities. It promotes learning through play, a concept embraced by educational institutions worldwide.

Additionally, LEGO® has established a global community of passionate fans, including AFOLs (Adult Fans of LEGO®), who continuously showcase the toy’s limitless possibilities through conventions, online platforms, and local communities.

The company’s commitment to sustainability is also noteworthy. It has pledged to make all its products from sustainable sources by 2030, setting a leading example in the industry.

Lastly, LEGO®’s successful ventures into entertainment media, including the highly popular “The LEGO® Movie” series and numerous LEGO®-themed video games, have further solidified its recognition and influence globally. These achievements illustrate how LEGO® has successfully transitioned from a simple toy to a powerful cultural phenomenon.

Innovations by LEGO®

Since its inception, LEGO® has been a beacon of innovation in the toy industry. Beginning with the simple interlocking brick system in the 1950s, the company has continually adapted and evolved to keep up with changing times and technologies. 

LEGO® introduced DUPLO® bricks in the 1960s, larger-sized blocks intended for younger children with less developed motor skills. In the 1970s, LEGO® expanded into the realm of fantasy with the launch of the first themed sets. In the 1980s, the company added a technical dimension with the Technic line, which incorporated complex mechanical elements like gears and axles. 

The 1990s saw the advent of LEGO® MINDSTORMS, a revolutionary line that combined traditional building with programmable robotics, integrating science, technology, engineering, and mathematics (STEM) concepts into play. More recently, LEGO® has been focusing on digital innovation, offering augmented reality experiences and interactive apps. 

Additionally, LEGO® has made strides towards inclusivity with Braille Bricks for visually impaired children and has committed to sustainability by pledging to use entirely sustainable materials in its products by 2030. These innovations have not only extended LEGO®’s product range but have also enhanced the depth and breadth of the experiences it offers.

How LEGO® Has Evolved Since Its Creation

Since the inception of the LEGO® brick in 1958, the company has been at the forefront of innovative play. What started as simple interlocking bricks has now expanded into a universe of its own, full of diverse themes, sophisticated models, and even programmable robotics.

The LEGO® System in Play was introduced in 1955, offering themed sets of bricks and encouraging structured play. This system laid the groundwork for the complex themed sets we see today, ranging from everyday city life to fantastical space exploration scenarios.

Another major milestone was the introduction of the LEGO® Minifigure in 1978. These small, articulated figures added a new dimension of role-play and storytelling to the LEGO® experience. They’ve since become iconic in their own right, with thousands of variations being produced.

In 1998, LEGO® further revolutionized the toy industry by merging traditional building play with digital technology through the LEGO® MINDSTORMS series. This introduced programmable robotics to LEGO® play, teaching kids coding and robotics principles.

A Comprehensive List of LEGO® Innovations and Their Significance

1. LEGO® DUPLO

Launched in 1969, LEGO® DUPLO is designed for younger children, featuring bricks that are twice the size of regular LEGO® bricks. This innovation widened LEGO®’s age demographic and made it more accessible for toddlers.

2. LEGO® Technic

Introduced in 1977, LEGO® Technic sets offer a more complex building experience, featuring advanced mechanical elements like gears, axles, and beams. This has appealed to older children and adults, expanding LEGO®’s reach.

3. LEGO® MINDSTORMS

MINDSTORMS series, introduced in 1998, allowed kids to create and program their own robotic creations, integrating STEM learning into play.

4. LEGO® Architecture

Launched in 2008, this series enables the building of famous architectural landmarks, appealing to both kids interested in architecture and adult enthusiasts.

5. LEGO® Ideas

Established in 2008, this platform allows fans to submit their own LEGO® set ideas. Winning designs are turned into official sets, making LEGO® co-creation a reality.

6. LEGO® Life

Introduced in 2017, LEGO® Life is a safe social media app for kids to share their creations, interact with each other, and engage in challenges set by LEGO®.

7. LEGO® Braille Bricks

Launched in 2020, these bricks are designed to help visually impaired children learn Braille in a playful and engaging way, showing LEGO®’s commitment to inclusivity.

Each of these innovations has helped LEGO® maintain its appeal and relevance over decades, contributing to the brand’s enduring success.

Other Widely Recognized Toys Worldwide

The global toy market is diverse and dynamic, with many products that have become iconic in their own right. Some of these include:

Barbie®

Barbie®, created by Mattel in 1959, has stood the test of time as one of the most iconic dolls in the world. This small fashion doll, introduced as a teenage fashion model, has evolved into an influential figure that has spanned over 60 years of changing societal norms and expectations.

Barbie® has been more than just a toy – she has been an astronaut, a doctor, a teacher, and a presidential candidate, among hundreds of other roles. This portrayal of various careers has been critical in encouraging young girls to envision a world with limitless possibilities.

In recent years, Mattel has taken strides to make Barbie® more inclusive and representative of diverse beauty standards. This is evident in the Barbie® Fashionistas™ line, which features dolls with a variety of body types, skin tones, hair types, and abilities. By continually evolving and keeping up with the times, Barbie® has managed to maintain its relevance and popularity in the toy market.

Hot Wheels®

Hot Wheels®, launched by Mattel in 1968, revolutionized the toy car industry by creating detailed and affordable model cars that were both playable and collectible. The brand’s initial success was due to the “California Custom” style cars, which featured hot rod designs with flashy paint jobs and big wheels. Hot Wheels® were faster and cooler looking compared to other toy cars in the market, making them instantly popular among kids.

Over the decades, Hot Wheels® has expanded its product range to include not just cars but tracks, playsets, and digital games. Their product line promotes creativity and hands-on play by allowing kids to build elaborate tracks and racing scenarios. With a focus on innovation and design, Hot Wheels® has captivated generations of children and has grown into a brand loved by collectors of all ages.

Transformers®

The Transformers® franchise, introduced by Hasbro in 1984, has had a profound impact on the toy industry. Its unique action figures, which could be transformed between robotic and vehicle modes, provided a novel and engaging play experience that captured the imaginations of millions of kids around the world. The Transformers® line was not just a toy but a rich universe with a storyline that spawned a successful animated television series, comics, movies, and video games.

Transformers® toys have evolved over the years, with new lines and characters being introduced to keep pace with the storyline developments in the various media adaptations. The toys appeal to both young children who enjoy the transformation aspect and the action figures, as well as older fans and collectors who appreciate the complexity and nostalgia of the brand.

Playmobil®

Playmobil®, a creation of the German Brandstätter Group, is a line of toys that have been stirring up kids’ imaginations since 1974. Each Playmobil® set is based on a specific theme and consists of figurines along with detailed accessories and playsets. The sets range from historical themes like “Romans and Egyptians” to modern-day scenarios like “City Life,” offering a broad palette for imaginative play.

Unlike LEGO®, which focuses on the building process, Playmobil® places more emphasis on role-playing and storytelling. The figures are ready to play with right out of the box, each with a distinct personality to inspire hours of play. This emphasis on imaginative play has made Playmobil® a beloved toy line globally and a strong competitor in the toy market.

NERF® Blasters

Hasbro’s NERF® brand, established in the late 1960s, has been synonymous with active, indoor-safe play. The brand’s first product was a foam-based ball, but it’s perhaps best known for its NERF® Blasters – toy guns that shoot soft foam darts. The Blasters offer a safe and fun way for kids to engage in competitive play without the risk of serious injury.

NERF® Blasters come in a wide variety of models, from small, handheld blasters to larger, battery-powered models with automatic fire. Hasbro continually innovates the line with new blasters, ammunition types, and associated gear, keeping the brand fresh and engaging. Today, NERF® is more than just a toy line; it’s a lifestyle brand that includes video games, apparel, and even competitive leagues.

Detailed Comparison of These Toys with LEGO®

LEGO® vs. Barbie®

While both LEGO® and Barbie® have significant standing in the toy industry, they cater to different aspects of play. Barbie®, with its wide range of dolls and accessories, promotes imaginative play through various scenarios and relationships. Kids can create stories, simulate real-life situations, and explore different roles and professions through Barbie® dolls. This focus on social and imaginative play allows children to express and understand emotions, nurturing their emotional intelligence.

In contrast, LEGO® stimulates creativity and cognitive development by offering a hands-on building experience. Children can create and manipulate their physical environment by building various models, sparking their imagination, and developing problem-solving skills. While LEGO® also offers a range of characters and scenarios for role-play, especially through its themed sets, it differs from Barbie® in the active construction aspect of the play.

LEGO® vs. Hot Wheels®

Hot Wheels® and LEGO® both provide vehicular play, but they approach it in different ways. Hot Wheels® focuses on car racing and collecting, offering a wide variety of model cars and race tracks. The brand emphasizes speed and action, as well as the aesthetic appeal of the model cars, fueling the passion for car racing and collection.

On the other hand, LEGO® offers a broader range of play experiences beyond vehicles. Its brick system allows children to build a multitude of structures, vehicles, and landscapes, encouraging creativity and problem-solving. LEGO® also has numerous vehicle sets, even licensed ones like LEGO® Speed Champions, allowing kids to build and play with models of real-world cars. But unlike Hot Wheels®, LEGO® vehicles are usually part of a larger set or theme, adding an extra layer of story and role-play.

LEGO® vs. Transformers®

Transformers® is a line of toys that blends action figures and vehicles, offering an engaging transformation mechanic. The brand is steeped in a rich storyline spanning multiple media platforms, from television series to movies. Transformers® toys offer both the action and adventure associated with the characters and the mechanical fascination of transformation.

LEGO®, while offering some sets with transformation elements like the 3-in-1 Creator sets, relies primarily on the versatility and creativity of its brick system. Its appeal lies in the endless possibilities that come with building and rebuilding. The process of following complex instructions to build a set also helps develop concentration and spatial awareness. While LEGO® has ventured into action-oriented sets, it does not focus on transformation as a primary play mechanic.

LEGO® vs. Playmobil®

Both LEGO® and Playmobil® offer a range of thematic playsets that encourage imaginative play. Playmobil® sets are known for their detailed figures and accessories, which represent a variety of themes and eras. The emphasis is on immediate play, as the sets require minimal assembly.

LEGO®, on the other hand, combines construction play with role-playing. Assembling a LEGO® set is a fundamental part of the play experience, fostering creativity and problem-solving skills. The process of building and modifying structures adds an extra layer of engagement before the role-playing begins. Both brands, therefore, stimulate imagination but cater to different aspects of play – Playmobil® focusing on scenario-based play and LEGO® on construction and creativity.

LEGO® vs. NERF® Blasters

NERF® Blasters provide a very different type of play experience compared to LEGO®. NERF® Blasters are designed for physical, active play, encouraging kids to move around and engage in competitive games. The foam-based toys offer a safe and fun way for kids to play out action-packed scenarios.

In contrast, LEGO® typically promotes a more cerebral and creative form of play. Building with LEGO® enhances fine motor skills, spatial awareness, and problem-solving abilities. While LEGO® has ventured into more action-oriented sets with themes like NINJAGO® and Super Heroes, it still maintains its focus on building and creativity. Thus, NERF® and LEGO® cater to different play needs – NERF® appeals to active, competitive play, and LEGO® to creative, constructive play.

The Unique Selling Points and Potential Shortcomings of Each Toy

Each of the aforementioned toys has unique selling points:

  1. Barbie®: Encourages social and imaginative play, and diverse representation in recent years.
  2. Hot Wheels®: Appeals to car enthusiasts, easy to collect and display.
  3. Transformers®: Unique transformation mechanics backed by a popular media franchise.
  4. Playmobil®: A variety of detailed playsets allows for immediate play.
  5. NERF® Blasters: Encourages active, physical play, and provides safe action-packed fun.

On the flip side, potential shortcomings include:

  1. Barbie®: Limited interactivity and construction elements compared to LEGO®.
  2. Hot Wheels®: Narrower focus (primarily cars) compared to LEGO®’s wide range of themes.
  3. Transformers®: Less creative input from the player in comparison to LEGO®.
  4. Playmobil®: Less building involved, which could limit creativity.
  5. NERF® Blasters: Limited in scope to active, combat-style play.

LEGO®, with its focus on creativity, construction, and play, offers a balance of active and imaginative play. While the building aspect may be challenging for younger children, LEGO® provides solutions like DUPLO®. However, it’s worth noting that no toy is objectively superior; the “best” toy depends on a child’s interests and developmental needs.

What Makes a Toy Great

The quality of a toy isn’t merely measured by its popularity or the amount of fun it offers. In fact, there’s a whole spectrum of factors that contribute to the greatness of a toy. Play Value is certainly the cornerstone of a good toy; it should be capable of maintaining a child’s interest over extended periods and ideally offer various ways to engage. 

The best toys encourage creativity, sparking a child’s imagination and allowing them to explore different play scenarios. In essence, these toys give children a form of self-expression and are flexible enough to evolve with a child’s interests and development.

However, play value is only one dimension. Educational Value is another critical factor, as toys should promote learning in some form. They may develop fine motor skills, problem-solving abilities, creativity, or social skills. Quality and durability are also paramount to ensure safety and longevity, especially given the rough treatment that some toys may endure. Toys must also be age-appropriate, challenging a child’s abilities without leading to frustration. Furthermore, they should be inclusive, reflecting the diversity of the real world. 

Finally, as environmental consciousness grows, the sustainability of a toy’s materials and its manufacture is increasingly important. Toys that stand the test of time often excel in many, if not all, of these aspects, striking a balance that caters to children’s needs and parents’ expectations.

1. Play Value

A great toy provides hours of engagement, not just a few minutes. It should stimulate the child’s imagination and offer multiple ways to play.

2. Educational Value

While not all toys need to be explicitly “educational,” they should encourage learning in some form, whether that’s fine motor skills, problem-solving, creativity, or social skills.

3. Quality and Durability

Toys should be well-made and withstand the test of time, not just for safety reasons but also because children often form emotional attachments to their favorite toys.

4. Age Appropriateness

Good toys are suited to the child’s developmental stage, challenging them but not frustrating them.

5. Safety

Toys must meet safety standards to ensure children can play without the risk of injury.

6. Inclusivity

In the modern toy market, diversity and representation in toys, as well as the ability to appeal to a wide range of children regardless of their background or abilities, are crucial.

7. Sustainability

As environmental consciousness grows, so does the demand for toys made from eco-friendly materials or those promoting sustainable practices.

How LEGO® and Other Toys Align with These Factors

1. LEGO®

With its countless combinations, LEGO® scores high on play value. It also has educational value, promoting fine motor skills, spatial awareness, creativity, and patience. LEGO® bricks are renowned for their quality and durability. They also offer sets for different age groups and abilities, ranging from DUPLO® to Technic and MINDSTORMS. 

Safety is paramount, with LEGO® adhering to strict safety standards. Their commitment to inclusivity can be seen in the wide range of themes and representation in minifigures, and LEGO® Braille Bricks are an excellent example of this. LEGO® is also making strides in sustainability, with a commitment to make all products from sustainable materials by 2030.

2. Other Toys

Other popular toys also align with these factors to varying degrees. For instance, Barbie® has made strides in inclusivity and representation in recent years. Hot Wheels® offers high play value for car enthusiasts and is known for its quality. 

Transformers® aligns with the factors of play value and age appropriateness, given their transformation mechanics and action-oriented play. Playmobil® offers immediate play value with less assembly and has a wide range of themes. 

NERF® Blasters offer active, physical play and meet safety standards by using foam-based ammunition. Sustainability varies among these brands, but more toy companies are moving towards eco-friendly practices due to rising consumer demand.

More Info

Is LEGO® only for children?

No, LEGO® is designed for builders of all ages. While some sets are specifically designed for children, others, like the LEGO® Architecture or Technic series, cater to older builders. Additionally, the AFOL (Adult Fans of LEGO®) community is thriving and widely recognized by the LEGO® Group.

Are LEGO® bricks eco-friendly?

LEGO® has committed to making its products more sustainable. By 2030, the company aims to manufacture all its bricks and packaging from sustainable materials. As of now, some LEGO® elements are already made from plant-based plastic sourced from sugarcane.

Is it true that Barbie® lacks diversity and inclusivity?

While earlier criticisms targeted Barbie® for lacking diversity, Mattel has made significant efforts in recent years to improve. The Barbie® Fashionistas™ line features dolls with a variety of body types, skin tones, eye colors, and hairstyles, showcasing a broader view of beauty.

How safe are NERF® Blasters?

NERF® Blasters are designed with safety in mind. The darts and missiles are made of soft foam to prevent injury. However, like any toy, they should be used responsibly, and eye protection is recommended during play.

Is Hot Wheels® just about car racing?

Primarily, yes, but Hot Wheels® offers more than just car racing. It also promotes the collection, customization of cars, and building of epic race tracks, encouraging creativity and hands-on play.

Do Transformers® toys have any educational value?

Yes, Transformers® toys can promote problem-solving and spatial reasoning skills as children figure out how to convert the toys between their different forms. They also stimulate imaginative play through storytelling and role-play scenarios.

Are Playmobil® and LEGO® competitors?

While both Playmobil® and LEGO® offer themed playsets that stimulate imagination, they differ significantly. Playmobil® focuses more on ready-to-play scenarios with less emphasis on building, while LEGO® encourages construction and creativity with its bricks.

What age is appropriate for LEGO® MINDSTORMS?

LEGO® recommends MINDSTORMS for ages 10 and up. These sets involve more complex building and programming, making them suitable for older children and teenagers interested in robotics and coding.

Conclusion

Through our comparative analysis, it’s clear that LEGO® holds a distinguished place in the global toy industry. While other toys have unique appeals and contribute in their own ways to the diversity of the toy market, LEGO® stands out with its enduring versatility, creativity, and commitment to education and quality. Its ability to continually innovate while staying true to its core brick system demonstrates a level of adaptability and resilience that’s key to its global success and longevity.

LEGO®’s numerous awards, including the “Toy of the Century” from both Fortune Magazine and the British Association of Toy Retailers, underline its status as a beloved and respected brand worldwide. Innovations like DUPLO®, Technic, MINDSTORMS, and more have allowed LEGO® to continually engage fans of all ages and expand its reach. Notably, LEGO® has also made strides in inclusivity, with efforts like the Braille Bricks, and sustainability, with its commitment to using sustainable materials.

Whether you’re an avid LEGO® builder or a newcomer to the brick-building world, we encourage you to explore the endless possibilities offered by LEGO®. Belle-Ve Bricks takes pride in bringing you a diverse range of LEGO® products to suit every interest, age, and skill level. From classic brick sets to advanced models, we have something to ignite every imagination. Step into the world of LEGO® with Belle-Ve Bricks, and let’s build something incredible together!

<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