Belle-Ve Bricks

Your Imagination

Complete Review of the LEGO® Titanic Set

Create Your

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

Intro

The Titanic, once the largest and most luxurious ocean liner in the world, set sail on her maiden voyage from Southampton, England to New York City on April 10, 1912. The vessel, touted as “unsinkable,” tragically met her fate on April 14, 1912, after colliding with an iceberg in the North Atlantic Ocean. Over 1,500 lives were lost, making the disaster one of the deadliest maritime tragedies in history. The Titanic’s story continues to captivate audiences worldwide, inspiring countless books, films, and memorials.

LEGO®’s homage to the Titanic

LEGO®, the world-renowned Danish toy company, has paid tribute to the Titanic by releasing a highly detailed, expert-level model of the ship. This impressive set not only offers a challenging and rewarding building experience but also serves as a historical reminder of the vessel’s incredible story.

Objectives of the article

This long-form article aims to provide a comprehensive review of the LEGO® Titanic set, covering every aspect from packaging and design to historical accuracy and community reception. We’ll examine the set’s unique features, explore its educational value, and delve into its significance in popular culture. Whether you’re a seasoned LEGO collector or simply captivated by the Titanic story, this review offers insights and analysis for everyone.

LEGO® Titanic Set Details and Specifications

1. Set number, piece count, and dimensions

The LEGO® Titanic set (set number 10294) consists of an astounding 9,090 pieces, making it one of the largest LEGO® sets ever produced. Once completed, the model measures over 53 inches (135 cm) long, 7 inches (18 cm) wide, and 17 inches (44 cm) high, truly capturing the grandeur and scale of the original ship.

2. Age recommendation and difficulty level

This expert-level set is designed for builders aged 18 and above, due to its complexity and intricate construction. The challenging nature of the build and the numerous advanced techniques used throughout the assembly process make the LEGO® Titanic an ideal choice for experienced builders seeking a rewarding project.

3. Price and availability

The LEGO® Titanic set is priced at $629.99, reflecting the scale and detail of the model. It can be purchased directly from LEGO®’s website, their official retail stores, or from various authorized resellers. Due to its popularity, the set may experience periods of limited availability.

LEGO® Titanic Box and Packaging

1. Box design and artwork

The LEGO® Titanic set comes in a large, elegantly designed box featuring a striking image of the completed model against a serene ocean backdrop. The box also showcases several close-up images of the set’s key features, offering a glimpse into the incredible detail and craftsmanship that awaits builders. The design pays homage to the Titanic’s legacy while emphasizing the grandeur of the set.

2. Unboxing experience

Upon opening the box, builders are greeted with a total of 46 bags of LEGO® bricks, thoughtfully organized and numbered to facilitate a smooth building process. The set also includes a comprehensive instruction manual that features not only step-by-step assembly instructions but also historical information about the Titanic and its significance.

3. Sorting and organization of pieces

Before diving into the build, it’s essential to sort the pieces by color, type, or bag number, depending on your preference. This step helps streamline the building process and minimizes the time spent searching for specific pieces. Many builders opt to use small containers or trays to keep the various parts organized and easily accessible.

Minifigures and Accessories

1. Minifigure characters and their roles

Although the LEGO® Titanic set does not include any minifigures, it’s worth noting that its scale doesn’t correspond to the traditional LEGO® minifigure size. However, this leaves room for creative builders to customize their set by adding minifigures inspired by the Titanic’s passengers and crew, such as Captain Edward Smith, ship architect Thomas Andrews, or even famous passengers like John Jacob Astor IV and Molly Brown.

2. Unique accessories and elements

The LEGO® Titanic set features numerous unique elements that contribute to the ship’s realistic appearance. Builders will appreciate the attention to detail in parts such as the printed tiles representing the ship’s name, the intricate funnel and mast elements, and the use of specialized pieces to capture the ship’s iconic curves and contours.

3. Comparisons with real-life counterparts

Although the set doesn’t include any minifigures or accessories directly related to the ship’s passengers and crew, it’s evident that the designers put significant effort into replicating the Titanic’s features as closely as possible. From the ship’s distinct hull design to its elaborate interior spaces, the LEGO® Titanic set is a faithful representation of the original vessel.

Building Techniques and Experience

1. Innovative building techniques

Throughout the construction process, builders will encounter various innovative building techniques that demonstrate the ingenuity of the set’s designers. Some examples include the use of Technic elements to ensure the ship’s structural stability, the incorporation of SNOT (Studs Not On Top) techniques for seamless aesthetics, and clever part usage to create the vessel’s intricate detailing.

2. Challenges faced during the build

Given the set’s complexity and size, builders will undoubtedly encounter some challenges along the way. Patience and attention to detail are essential, especially when working on the ship’s more intricate sections, such as the Grand Staircase and the curved hull. It’s crucial to carefully follow the instruction manual to avoid any errors that could impact the overall building experience.

3. Estimated time for completion

The LEGO® Titanic set is a substantial project that will likely take experienced builders anywhere from 20 to 30 hours to complete, depending on their skill level and pace. It’s essential to allocate sufficient time and space for the build, ensuring a comfortable and enjoyable experience.

Set Sections and Subassemblies

1. Bow section

The bow section of the LEGO® Titanic set is expertly designed to capture the ship’s iconic silhouette. Builders will enjoy assembling the vessel’s intricate hull and forecastle deck, complete with details such as the cargo cranes, anchor chains, and mooring ropes.

2. Midship section

The midship section is home to some of the ship’s most iconic features, such as the Grand Staircase, first-class accommodations, and the lavish dining saloon. This section of the build offers a fascinating glimpse into the opulence and grandeur of the Titanic’s interior spaces.

3. Stern section

As builders work their way towards the stern section, they’ll encounter the ship’s aft decks, engine room, and boiler rooms. This portion of the set showcases the inner workings of the vessel, providing a captivating look at the engineering marvels that powered the Titanic on her fateful journey.

Exterior Design and Features

1. Hull construction and detailing

The LEGO® Titanic sets hull is a marvel of design, employing advanced building techniques to capture the ship’s sleek lines and distinct shape. Throughout the assembly process, builders will appreciate the intricacies of the hull’s construction, from the use of curved elements to create the vessel’s contours to the careful placement of tiles for a seamless appearance.

2. Deck features and layout

The set’s deck spaces are meticulously designed to replicate the Titanic’s features accurately. Key elements such as the cargo cranes, lifeboats, and various deck fixtures are all present, allowing builders to appreciate the ship’s impressive scale and attention to detail.

3. Funnel and mast details

The LEGO® Titanic set includes all four of the ship’s iconic funnels, each expertly crafted to resemble the originals. In addition to the funnels, the set also features detailed masts complete with rigging and crow’s nests, providing yet another layer of authenticity to the model.

Interior Design and Features

1. Grand staircase and reception area

One of the most iconic features of the Titanic is the Grand Staircase, and the LEGO® set does not disappoint. The elegantly designed staircase, complete with its intricate balustrade and ornate clock, serves as the centerpiece for the ship’s reception area. This section of the building offers a fascinating glimpse into the opulence and grandeur of the Titanic’s interior spaces.

2. First-class cabins and dining saloon

The LEGO® Titanic set showcases the vessel’s luxurious first-class accommodations, including lavish cabins and a stunning dining saloon. These intricately designed spaces provide builders with a sense of the extravagance and elegance that the Titanic’s wealthy passengers experienced during their voyage.

3. Engine room and boiler rooms

The set also delves into the ship’s inner workings, featuring detailed representations of the engine room and boiler rooms. These sections allow builders to explore the engineering marvels that powered the Titanic and appreciate the immense scale of the machinery that lay beneath the ship’s opulent exterior.

Stability and Display Options

1. Structural integrity

Despite its size and complexity, the LEGO® Titanic set boasts excellent structural integrity. The use of Technic elements and well-engineered connections ensures the model remains stable and secure throughout the building process and during display.

2. Stand design and functionality

The set includes a specially designed display stand that not only provides support for the massive model but also adds an elegant touch to the overall presentation. The stand features the ship’s name and vital statistics, further emphasizing the set’s historical significance.

3. Display considerations and recommendations

Due to its size and weight, the LEGO® Titanic set requires a significant amount of space for display. It’s essential to choose a sturdy, flat surface that can accommodate the model’s dimensions and consider factors such as lighting and protection from dust or damage.

Comparison with Other LEGO® Ship Sets

1. LEGO® Viking Ship and the Midgard Serpent

Set Number: 7018
Theme: Vikings
Year Released: 2005
No. Pieces: 578
RRP: $49.99

Embark on a mythical journey with this Viking Ship set. While the Titanic showcases historical elegance, this set invites you to explore Norse legends. Its fearsome Midgard Serpent adds a fantastical touch that contrasts with the Titanic’s realism, offering a thrilling adventure for those fascinated by mythology.

2. LEGO® Nightmare Shark Ship 71469

Set Number: 71469
Theme: DREAMZZZ
Year Released: 2023
No. Pieces: 1389
RRP: £119.99 / $139.99 / €139.99

Dive into the mysterious world of Atlantis with the Nightmare Shark Ship. Unlike the Titanic’s grand interiors, this set plunges you into an underwater realm. Its shark motif and fantastical design provide a unique exploration experience that complements the Titanic’s historical focus, sparking curiosity about the unknown depths.

3. LEGO® Pirate Ship 31109

Set Number: 31109
Theme: Creator
Year Released: 2020
No. Pieces: 1264
RRP: £114.99 / $119.99 / €129.99

Set sail on a classic pirate adventure with this Pirate Ship. While the Titanic offers a glimpse into maritime history, this set captures the romance of the high seas. With cannons, sails, and pirate minifigures, it provides a swashbuckling experience that contrasts with the Titanic’s elegance, igniting imagination and adventure.

4. LEGO® Arctic Explorer Ship 60368

Set Number: 60368
Theme: City
Year Released: 2023
No. Pieces: 815
RRP: £129.99 / $159.99 / €149.99

Explore the icy frontiers with the Arctic Explorer Ship. Unlike the Titanic’s colossal achievement, this set focuses on modern exploration. Its icebreaker ship and arctic-themed accessories offer a fresh perspective on maritime adventure, appealing to those intrigued by the challenges of arctic exploration.

Retired LEGO® Ship Sets

1. LEGO® Ideas Ship in a Bottle 92177

Set Number: 92177
Theme: Ideas
Year Released: 2020 (retired 2021)
No. Pieces: 962
RRP: £69.99 / $69.99 / €69.99

The LEGO® Ideas Ship in a Bottle (set number 92177) is a unique, display-worthy set that features a miniature ship enclosed within a transparent brick-built bottle. While considerably smaller and less complex than the Titanic set, the Ship in a Bottle offers a charming building experience that appeals to maritime enthusiasts and collectors alike.

2. LEGO® Creator Expert Maersk Triple-E 10241

Set Number: 10241
Theme: Expert
Year Released: 2014 (retired 2014)
No. Pieces: 1518
RRP: £109.99 / $149.99 / €129.99

The LEGO® Creator Expert Maersk Triple-E (set number 10241) is a highly detailed model of one of the world’s largest container ships. Although not as historically significant as the Titanic, the Maersk Triple-E set showcases LEGO®’s commitment to designing accurate, large-scale ship models that cater to both builders and maritime aficionados.

3. LEGO® City Ocean Exploration Ship 60266

Set Number: 60266
Theme: City
Year Released: 2020 (retired 2021)
No. Pieces: 745
RRP: £124.99/$149.99/€129.99

The LEGO® City Ocean Exploration Ship (set number 60266) is a fun and interactive set designed for younger builders. While less intricate and historically focused than the Titanic set, it offers an engaging play experience complete with minifigures, a shipwreck, and various marine life elements.

Historical Accuracy and Educational Value

1. Comparison with the real Titanic

The LEGO® Group’s commitment to accuracy in the representation of the Titanic is evident in their extensive research and collaboration with experts. Designers have studied photographs, blueprints, and historical documents related to the Titanic to ensure a faithful representation. Collaboration with maritime historians and experts has further enriched the design process, adding layers of authenticity to the final product.

Attention to detail is a hallmark of the LEGO® Titanic set. The ship’s distinct hull shape, funnels, and carefully crafted interiors are replicated with precision using LEGO® bricks. For example, the set consists of over 9,000 pieces, allowing for intricate detailing that mirrors the original vessel’s design.

The use of specialized pieces and building techniques has been instrumental in achieving an accurate representation of the Titanic. The LEGO® Group has employed unique elements to capture the ship’s unique features, such as the grand staircase and the engine room, further enhancing the realism of the set.

Quality control and review are integral to the LEGO® Group’s design process. Multiple stages of review ensure that the final product aligns with the historical accuracy of the Titanic. This commitment to quality has made the LEGO® Titanic set a sought-after collector’s item.

2. Insights into Titanic’s History and Legacy

The set’s accompanying instruction manual includes historical information about the Titanic and its significance, offering builders the opportunity to learn about the ship’s construction, maiden voyage, and tragic sinking. The LEGO® Titanic set serves as a valuable educational tool, sparking interest in maritime history and engineering.

Historical Context and Construction Details

The set’s instruction manual provides a comprehensive overview of the Titanic’s history, including its construction. Built in Belfast by Harland and Wolff, the Titanic was a marvel of engineering during its time. It was one of the largest and most luxurious ships ever built, involving over 15,000 workers and taking more than two years to complete. The manual includes details about the ship’s design, the materials used, and the innovative engineering techniques employed (Source: Encyclopedia Britannica).

Maiden Voyage and Societal Impact

The LEGO® Titanic set also explores the ship’s maiden voyage from Southampton to New York. It delves into the passengers’ experiences, the ship’s route, and the societal excitement surrounding this “unsinkable” vessel. The Titanic represented the technological advancement and optimism of the early 20th century, symbolizing human ambition and progress.

Tragic Sinking and Lessons Learned

The tragic sinking of the Titanic on April 15, 1912, after colliding with an iceberg, is a significant part of the set’s educational content. More than 1,500 lives were lost in the disaster. This tragedy led to a reevaluation of maritime safety regulations and practices. New laws were enacted, including improvements in lifeboat requirements and the establishment of the International Ice Patrol to monitor iceberg threats (Source: International Maritime Organization).

Educational Value and Legacy

Beyond the building experience, the LEGO® Titanic set serves as a valuable educational tool, sparking interest in maritime history, engineering, and ethics. It encourages reflection on human triumphs, ambitions, and the lessons learned from tragedy. The set’s detailed design and accompanying historical information make it a tangible connection to the past, allowing builders to engage with the Titanic’s legacy in a unique and meaningful way.

3. Opportunities for learning through building With LEGO®

The LEGO® Titanic set offers an engaging, hands-on learning experience that encourages builders to develop their problem-solving, critical thinking and fine motor skills. Assembling the model not only fosters an understanding of the ship’s design and history but also cultivates a sense of accomplishment and pride in completing such an intricate and challenging project.

1. Development of Problem-Solving Skills

Assembling the LEGO® Titanic set requires builders to follow complex instructions, interpret diagrams, and figure out how various pieces fit together. This process encourages the development of problem-solving skills, as builders must think critically and creatively to overcome challenges and construct the model accurately.

2. Enhancement of Critical Thinking

The intricate design of the LEGO® Titanic set demands careful planning and attention to detail. Builders must analyze the instructions, understand the sequence of assembly, and make decisions about how to proceed. This fosters critical thinking skills, enhancing the ability to analyze information and make reasoned judgments.

3. Improvement of Fine Motor Skills

The LEGO® Titanic set consists of over 9,000 pieces, some of which are quite small and require precise placement. Handling these pieces and assembling them into the larger structure helps improve fine motor skills, promoting hand-eye coordination and dexterity.

4. Connection to History and Engineering

Beyond the physical building process, the set offers insights into the Titanic’s design, history, and legacy. This connection to real-world engineering and historical events adds an educational dimension to the building experience, encouraging curiosity and exploration of maritime history and engineering principles.

5. Sense of Accomplishment and Pride

Completing the LEGO® Titanic set is a significant achievement, given its complexity and size. The sense of accomplishment and pride in building such an intricate and challenging project can boost confidence and provide a tangible demonstration of perseverance and skill.

Customization and Expansion Possibilities

1. Lighting and effects

Many LEGO® enthusiasts choose to enhance their Titanic model by adding custom lighting elements to highlight the ship’s features and create a more immersive display. Various third-party companies offer specialized lighting kits designed specifically for the LEGO Titanic set, allowing builders to illuminate the ship’s exterior, decks, and interior spaces.

2. Modifications for added detail

Skilled builders may opt to modify their LEGO® Titanic set to incorporate even more detail and accuracy, drawing inspiration from historical photographs, blueprints, and other resources. Customizations can include adding extra lifeboats, recreating specific passenger cabins, or even expanding the ship’s intricate interiors.

3. Complementary sets and extensions

While the LEGO® Titanic set is a standalone model, builders may choose to complement their display with additional maritime-themed sets or accessories. These can range from a custom iceberg or ocean dioramas to the inclusion of other iconic ships from history, creating an impressive collection that showcases the world’s most famous and fascinating vessels.

How People Customize Their LEGO® Sets

1. Personalization of Existing Sets

Many builders choose to personalize existing LEGO® sets by adding unique touches or modifying certain elements. This can include changing colors, adding decorative details, or altering the design to better reflect their personal tastes or interests. The LEGO® community often shares these customizations online, inspiring others to try similar modifications.

2. Expansion and Integration

Some builders take customization a step further by expanding on existing sets, integrating them into larger displays or dioramas. This can involve connecting multiple sets, building additional structures, or creating landscapes to provide context. For example, a LEGO® cityscape might be expanded with custom roads, parks, and buildings to create a more comprehensive and immersive scene.

3. Creation of Original Models (MOCs)

Many LEGO® enthusiasts design and build their own original models, known as My Own Creations (MOCs). These can range from small, simple designs to highly complex and intricate structures. MOCs often showcase incredible creativity and skill, and there are online platforms and communities dedicated to sharing and celebrating these original works.

4. Utilization of Third-Party Services

Companies like the Belle-Ve Bricks team offer customization services to enhance the LEGO® experience. These services can include designing specific alterations to existing sets or creating entirely new custom models based on a customer’s vision. This professional approach to customization has broadened the possibilities for LEGO® builders seeking unique and personalized creations.

5. Educational and Therapeutic Applications

Customizing LEGO® sets is not only a recreational activity but also has educational and therapeutic applications. Schools and therapy centers may use LEGO® building and customization as tools to foster creativity, problem-solving, teamwork, and fine motor skills.

Community Reception and Reviews

1. Overall impressions

The LEGO® Titanic set has been widely praised by both the LEGO® community and Titanic enthusiasts for its incredible level of detail, accuracy, and impressive size. Many builders have commended the set’s challenging yet rewarding building experience, as well as the historical and educational aspects it offers.

2. Expert reviews

Numerous LEGO® experts and reviewers have lauded the Titanic set for its innovative design, advanced building techniques, and faithful representation of the original ship. They have noted that the set stands out as a testament to LEGO®’s commitment to creating high-quality, expert-level models that cater to a diverse audience of builders and collectors.

3. User testimonials

Many builders who have completed the LEGO® Titanic set have shared their positive experiences and personal connections with the model, describing the build as a captivating and immersive journey into the Titanic’s history. Users have also appreciated the set’s educational value and the opportunities it provides for creative customization and expansion.

More Info

1. How many pieces are in the LEGO® Titanic set?

The LEGO® Titanic set contains a total of 9,090 pieces. This extensive number of pieces contributes to the set’s intricate detailing and complexity, allowing for a faithful representation of the original vessel. It’s one of the largest LEGO® sets available, providing a challenging and rewarding building experience.

2. What is the age recommendation for the LEGO® Titanic set?

The set is recommended for builders aged 18 and above. This age recommendation reflects the complexity and intricate construction of the model. With over 9,000 pieces and detailed instructions, the set is designed to provide an engaging and satisfying experience for adult builders and enthusiasts.

3. How much does the LEGO® Titanic set cost?

The LEGO® Titanic set is priced at $629.99. This price point reflects the set’s size, complexity, and the quality of the materials used. It’s a premium set that offers a high level of detail and accuracy, making it a valuable addition to any LEGO® collection or a meaningful gift for maritime history enthusiasts.

4. What are the dimensions of the completed LEGO® Titanic model?

The completed LEGO® Titanic model measures over 53 inches (135 cm) long, 7 inches (18 cm) wide, and 17 inches (44 cm) high. These dimensions make it one of the largest LEGO® models available, capturing the grandeur and elegance of the original ship. Its impressive size adds to the display value of the model, making it a standout piece in any collection.

5. Does the LEGO® Titanic set come with any minifigures?

The LEGO® Titanic set does not include any minifigures, as its scale does not correspond to the traditional LEGO® minifigure size. The focus of this set is on the architectural and historical accuracy of the ship itself, rather than on individual characters. The absence of minifigures allows for a more realistic portrayal of the ship at its actual scale.

Conclusion

Overall assessment

The LEGO® Titanic set is a stunning and meticulously crafted tribute to the iconic ocean liner, offering a challenging and immersive building experience that is both educational and enjoyable. With its remarkable attention to detail, advanced building techniques, and impressive size, the set is a must-have for LEGO enthusiasts, Titanic fans, and history buffs alike.

Value for collectors

As one of the largest and most intricate LEGO® sets ever produced, the Titanic holds significant value for collectors, who will appreciate the model’s historical significance and exceptional craftsmanship. The set is a worthy addition to any LEGO® collection and is sure to be a conversation starter for years to come.

Final thoughts

The LEGO® Titanic set stands as a remarkable achievement in LEGO® design and a fitting homage to the legendary ship’s history. By capturing the Titanic’s essence in brick form, the set invites builders to embark on a fascinating journey of discovery and exploration, fostering a deeper appreciation for the ship’s enduring legacy.

<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