Anonymous Girl
Anonymous Girl

Reputation: 642

Execute Script tag using JS instead of PHP

I have a case in php, where I execute <script> tag of Adsense, if the userAgent is not BOT, but for some good reason I want to execute it using JS.

Helper Function:

function detectBottypes() {
        $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(!empty($userAgent) and preg_match('~(bot|crawl|google|lighthouse|spider|feedparser|crawler|pinterest)~i', $userAgent)) {
            return true;
        }
        return false;
}

in View:

    @if( Request::is('photo/*') && detectBottypes()==false )

        <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" crossorigin="anonymous"> 
        </script>

    @endif

Above, if request is photo/* and not bot then it is rendered in view, but I want it to be rendered in either of cases but only executed for the specific case. I have the case of JS

       window.onload = function () {
            var agent = navigator.userAgent.toLowerCase();
            if (agent.indexOf('bot') != -1) { 
              // ******* Execute here ********
            }
            else {
               
            }
       }

Reason why I want: I cache the view file to skip the load on server, so if the page is first crawled by Bot(Google) it is cached without the above case of Adsense Script ( Ad is not loaded to Bot) but since it is cached if later it is viewed by real user, the cached version without Ads is shown which I do not want, so preferred to be with JS

Upvotes: 2

Views: 111

Answers (1)

apokryfos
apokryfos

Reputation: 40673

You can dynamically load a script with something like:

window.onload = function () {
    var agent = navigator.userAgent.toLowerCase();
    if (agent.indexOf('bot') != -1) { 
       var scriptTag = document.createElement('script'); 
       scriptTag.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
       scriptTag.async = true;
       scriptTag.type = 'text/javascript';
       scriptTag.crossorigin = 'anonymous';
       document.head.prepend(scriptTag);
    } else {
    
    }
}

This should cause the browser to download and run the script. However there's a broader question on your use of caching. It may be simpler if you cache two versions of the content and serve each one based on the UA, if that is an option.

Upvotes: 2

Related Questions