Dynamically and asynchronously loading numerous LinkedIn share buttons on a page

On my page, I have a grid of post thumbnails that are fetched via AJAX and can be filtered. When a user clicks on a thumbnail, a carousel opens with the selected post centered. In this carousel, each post has a LinkedIn share button integrated.

The issue arises when trying to load the LinkedIn share buttons into an invisible element initially and then making it visible later. This causes the buttons not to work properly. To solve this problem, I use the code snippet below:

$.getScript('http://platform.linkedin.com/in.js', function() { 
  $('.li-box-1').append('<script type="IN/Share" data-counter="right"></script>');
});

However, if I close the carousel, filter the posts, select a different one, and open the carousel again, the LinkedIn share button is missing. Additionally, a warning appears in the console stating:

duplicate in.js loaded, any parameters will be ignored

This warning occurs because LinkedIn's in.js script has already been loaded previously. Does anyone have a solution for this issue?

Answer №1

Below is the snippet of code that will include the mandatory linked in .js library. We first check if the library has been loaded before by verifying if the variable IN is undefined. Depending on this condition, we either load the library for the first time or skip the process.
This piece of code should be placed within your <header> section, following the <body> tag, or just before the closing </body>, depending on your specific case.

<script>
if (typeof (IN) !== 'undefined') {
  // IN.parse(); // old but still supports
  IN.init();  // reinitiating linkedin button  
} else {
  $.getScript("http://platform.linkedin.com/in.js");
}   
</script>  

Alternatively, you can also utilize the following method:

<script>
  delete IN;
  $.getScript("http://platform.linkedin.com/in.js")
</script>

Now, place this code alongside your custom carousel or carousel items.

<script type="IN/Share" 
        data-url=" **code to generate your url** " 
        data-counter="right">
</script>

Answer №2

Upon examining the script being executed, one can observe that the output of the .getScript function is not directly injected into the script tag itself; rather, two distinct actions are taking place: loading the script and then generating the tag with type="IN/Share". The initial step of loading the script only needs to be performed once, as previously noted, hence it suffices to execute the .append command to create any desired dynamic buttons and subsequently invoke IN.parse() to establish a connection between the script and the freshly generated elements.

Answer №3

It seems like you're utilizing some advanced coding techniques just to share a link on LinkedIn. Have you considered trying a simpler method?

https://www.linkedin.com/sharing/share-offsite/?url={url}

This way, you'll have the flexibility to hyperlink anything you desire, customize it with CSS and JS, and more.

Source: Microsoft LinkedIn Share URL Documentation.

Here's an example that works for me:

It functions perfectly:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Azure API Management encountering Cross-Origin Resource Sharing (CORS) problem

Utilizing Azure API management to interact with my Python Flask web service has been efficient for GET operations. However, encountering an issue when attempting POST requests using jQuery AJAX calls where the request is converted to OPTIONS resulting in t ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Integrating additional youngsters into the HTML DOM using Angular.js

I am working with a block of HTML that looks like this: <div id="parent"> <div id="child_1"></div> <div id="child_2"></div> <div id="child_3"></div> <div id="child_4"></div> </div> ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

Switching from a click event to a hover event in JavaScript

I've been experimenting with animating a burger bar on hover and came across an example online that I managed to adapt for mouseenter functionality. However, I'm struggling to make it revert back to the burger bar shape once the mouse leaves on m ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

Comparison of getComputedStyle() and cssText functionality between Internet Explorer and Firefox

Take a look at this example to see the issue in action. I'm attempting to access the cssText property of a <div> using window.getComputedStyle(element) (which provides a CSSStyleDeclaration object). While this works smoothly in Chrome, it' ...

Show the chosen option when the textarea is no longer in focus

My form includes a text box and a button: <p><textarea rows="4" cols="30">Aliquam erat volutpat.</textarea></p> <p><input type="button" value="Submit"></p> When the user selects text in the textarea and then cl ...

"Triggering ngClick causes ngSrc to update, however, the keydown event handler does not have

Currently, I am developing a dynamic live map application that includes various navigation buttons like pan and zoom. To enable keyboard control, I have implemented a keydown event handler that triggers the same function as the button clicks. Interestingl ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

Enhance your checkbox and radio components with React Higher Order Components (H

I'm in the process of designing my own custom checkbox and radio components to ensure reusability. This is what I have so far: import React, { Component } from 'react' export class Checkbox extends Component { render() { return ...

Tips for choosing a single row in a table using a checkbox

I need help with a table that has multiple rows and four columns. One column is for checkboxes, while the other three are select boxes set to read-only. I want users to be able to edit only one row at a time by checking the checkbox in the first column. If ...

What is the best way to handle parsing JSON with special characters in JavaScript?

Content stored in my database: "Recommended cutting conditions" When using Json_encode in PHP, the result is: {"table1":[{"Item":{"original_text":"\u63a8\u5968\u5207\u524a\u6761\u4ef6 \b"}}]}; In JavaScript : var str ...

The Rails base file contains a function, let's call it function A, which calls another function, function C. However, function C is defined in two separate JavaScript files

My project includes an application_base.js file with a function: function drawLocations(canvas, blag, blah) { //do some stuff selectLocations(a_something, b_something); //do some stuff } For Page 1: page_1.js function selectLocations(a_somet ...

Learn how to showcase a modal pop-up in AngularJS by utilizing the ng-if directive

Hello, I am new to working with AngularJS. My question is how can I display a modal pop-up box when the ng-if statement evaluates to false? Can you please provide guidance on how to solve this issue? Here is an example of the code snippet in HTML: <di ...