How to Dynamically add Javascript to Visualforce Page

You may encounter a situation where you are supposed to inject a javascript on visualforce page conditionally. Let suppose a case where you detect device of landing page and inject javascript conditionally after finding device  I am sharing a piece of snippet which actually allow you to inject Javascript dynamically. This can also be achieve using jQuery as well

This is fairly simple, the one method I designed here  check if the device is mobile (isMobile()) which in return be used later on as condition to inject the script. If device is mobile then I inject the script

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
//@Author - Harshit Pandey
//@Source -http://www.oyecode.com
 
<!-- ============================================================ -->
<!-- ======== Script for Mobile and Custom Design Tweaks ====== -->
<!-- ============================================================ -->
//Check if the browser agent in Mobile
function isMobile() {
if( navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else
{
return false;
}
}
//** Majority of Hand Held device handles multi-piclist selection
// with own custom way of handling them
// For web-version we need a special script called Bootstrap-Select
// Go here - http://silviomoreto.github.io/bootstrap-select/
// We are adding this script to give similar experience to end user
//Load Javascript based on Device of End-User
function loadConditionalScript()
{
//Set Location of Script
var jHead = document.getElementsByTagName('head')[0];
//Create Script Tag
var jScript = document.createElement('script');
//Add Source of Script
var source = https://cs12.salesforce.com/resource/1372471384000/GoogleMapHP/GoogleMap/js/map.js;
//Set Attributes
jScript.setAttribute("type", "text/javascript");
jScript.setAttribute("src", source);
//Check if Mobile
if(!isMobile())
{
//if Mobile
//Insert Script Dynamically
jHead.appendChild(jScript);
}
}
view rawgistfile1.js hosted with ❤ by GitHub

Post a Comment