开发者

Calling function to execute javascript code

开发者 https://www.devze.com 2023-04-07 21:29 出处:网络
I would like to place a javascript (adsense) code inside the post (not above or after the post). It will be a HTML page.

I would like to place a javascript (adsense) code inside the post (not above or after the post). It will be a HTML page.

Is there any way i can put my adsense code in external Js file and i will use one function to display it. adsense code looks something like

<scrip开发者_StackOverflow中文版t type="text/javascript"><!--
google_ad_client = "pub-xxxxxxxxxxxxxxxx";
google_ad_host = "pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

So if i call a function CallMe() which will start showing ad wherever i have used the function. In future if i would like to replace ad code with another code then i dont want to go to each post and replace it. I will just replace the adcode from js file.

I am a newbie and have just started learning JavaScript so i am really not aware if it can be done or not.

Any suggestion ?


Create file called AdSense.js with the following code:

google_ad_client = "pub-xxxxxxxxxxxxxxxx";
google_ad_host = "pub-xxxxxxxxxxxxxxxx";
google_ad_slot = "xxxxxxxxxx";
google_ad_width = 336;
google_ad_height = 280;
function ApplyAdSense() {
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = "http://pagead2.googlesyndication.com/pagead/show_ads.js";
    document.getElementsByTagName("head")[0].appendChild(oScript);
}

Now whenever you want adsense in your code, first include the file:

<script type="text/javascript" src="AdSense.js"></script>

Then call the function:

<script type="text/javascript">
    ApplyAdSense();
</script>

This way, until you call the function nothing happens.. and you can also comment the code inside the function to disable adsense throughout all your site.


Wherever you want the ad to show up, place this code (assuming you have a function called CallMe).

    <some html>
        <script type="text/javascript">CallMe();</script>
    </some html>


If your concern is about the page loading time, Adsense released the asynchronous version of their Adsense code. Please see https://support.google.com/adsense/answer/3221666?hl=en

0

精彩评论

暂无评论...
验证码 换一张
取 消