Lazy Panda

Developer

Posts
57
Comments
48
Likes
76
Posts
57
Comments
48
Likes
76
sidebar

How to add Google AdSense Script tag programmatically using JavaScript or Angular 11

I have written an article and I am not able to add any AdSense script inside my article. And I was thinking about how can I add Google AdSense code snippets into my blog's HTML. As my blog's content is simple HTML, generated by custom-made CMS (Content management system) which was built by me as well. But while creating the content I always focus on content text or images, using that I can demonstrate the purpose of the article. But when I am publishing it, I do need to monetize it as well. Let's see how it was looking like just after creating content.

add-script-tag-programatically

 

In the above you can see, the content is written in simple HTML which is actually generated using an editor created by me. The editor has some limitations, I can not include any script tag while creating content. As a result, I can not include the Google AdSense code while creating content. I need to add the code snippets in between two paragraphs by run time. So the content could be seen properly with Google ads. 

 


What I want to achieve here...

I want to add Google AdSense code snippets between two paragraphs.

add-script-tag-programatically

 

To achieve my goal, I add a simple id with a div tag. While adding the code into the main page template, the code will search the respective id and place the required script tag between two divs. 

add-script-tag-programatically

Once the respective id has been added into the HTML, I need to search that id and place the AdSense JavaScript code.

 

injectAdSense = (htmlString: string, idCount: number) => {

const domParser = new DOMParser();
const htmlElement = domParser.parseFromString(htmlString, 'text/html');

 

for (let index = 1; index <= idCount; index++) {

const adSnippets = htmlElement.getElementById(`lazy-loaded-ad-${index}`);

if (adSnippets) {

// Keep this line, if the url not included in header section

// const adsenseNodeCreation = window.document.createElement('script');

// adsenseNodeCreation.async = true;

// adsenseNodeCreation.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';

// end

 

const insHtml = window.document.createElement('ins');

insHtml.className = 'adsbygoogle';

insHtml.style.display = 'block';

insHtml.style.textAlign = 'center';

insHtml.setAttribute('data-ad-format', 'fluid');

insHtml.setAttribute('data-ad-layout', 'in-article');

insHtml.setAttribute('data-ad-client', 'ca-pub-27113xxxxxxxxx');

insHtml.setAttribute('data-ad-slot', '347xxxxxxx');

 

// adSnippets.appendChild(adsenseNodeCreation);

adSnippets.appendChild(insHtml);

}

}

return htmlElement.body;

}

 

 

To call the method, I have used in following way -

const blogDetails = this.injectAdSense(description, 2); Where the first parameter description is the HTML code and data type is String. The second parameter is the number of AdSense id being added into the HTML.

document.getElementById('my-blog').appendChild(blogDetails);

Once you have done the changes, it could look as follows - 

 

add-script-tag-programatically

 

Now the most important part of this article is, you need to get In-view and out-view point, where you can inject the script tag programmatically. Whenever the div shows in viewport based on user scroll action, we will load the AdSense script lazily on the viewport. 

add-script-tag-lazy-loading

 

 

To get the user scroll action we need to watch window.scroll event. Using angular I am using @HostListener to get the scroll position. Like below 

@HostListener('window:scroll') onScroll(e: Event): void {

for (let i = 1; i <= this.totalNumberOfAds; i++) {

this.isItInView(`lazy-loaded-ad-${i}`);

}

}

 

Above method will execute whenever user scroll the page, we are going to validate the id of corrosponding div is in-view or out-view. 

isItInView(id: string) {

const adsElement: HTMLElement = document.getElementById(id);

if (adsElement) {

const bounding = adsElement.getBoundingClientRect();

if (

bounding.top >= 0 &&

bounding.left >= 0 &&

bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&

bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)

) {

if (!this.isAdsLoaded.includes(id)) {

this.isAdsLoaded.push(id);

this.loadAdsScriptDynamically(id);

} else {

const adscriptElement: HTMLElement = document.getElementById('ads');

if (adscriptElement) {

adscriptElement.remove();

}

}

}

}

}

 

The above function will exactly tell you the particular targetted div is in-view or out view, if the id is outside of the view we are going to remove that id. And if it is inside the view we are going to execute the script value. Let's how I am calling the script. 

I have created a script loader service, which helps to load external script files. And from angular, I am sending targetted div id, and based on this id it will going to execute the AdSense code snippets. 

 

Also the script loader, you need to pass the path the of external script (js) file. Like below -

 

You are almost done with setup, only the part remains what is it in ga-lazy.js file and how I am calling the function. 

ga-lazy.js

$(document).ready(function() {

var scriptTag = document.getElementById('ads');

var key = scriptTag.getAttribute('data-name');

(adsbygoogle = window.adsbygoogle || []);

$("<script>(adsbygoogle = window.adsbygoogle || []).push({})</script>").appendTo(key);

eval((adsbygoogle = window.adsbygoogle || []).push({}));

});

}

 

How am I executing the script?

loadAdsScriptDynamically(id: string) {

this.scriptLoader.load(`#${id}`, 'google-ads').then(data => {

console.log('data: ', data);

}).catch(err => {

console.log(err);

});

}

 

 

You are ready with setup, now you can deploy the site and you can see the ads are showing the middle of your article as user scroll. If you find this post is useful to you please share and comments below.

Happy Coding!

- LP