Hey all im trying something (because im boring) every function as js files can be used but if only needed file will bi apended. so i have write something like this. some parts from this site.
library.js:
var jsfiles = new Array(
"jsLibrary/try.js",
"jsLibrary/try2.js"
);
var loadedJsFiles = [];
function loadFile(filepath,callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = filepath;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
function loadalljs(callback,jsnum){
if(!jsnum){jsnum = 0;}
if(jsnum<jsfiles.length){
if(!isArrayNode(jsfiles[jsnum],loadedJsFiles)){
loadedJsFiles.push(jsfiles[jsnum]);
loadFile(jsfiles[jsnum],function(){
loadalljs(callback,jsnum+1);
});
}else{
loadalljs(callback,jsnum+1);
}
}else if(jsnum==jsfiles.length){
callback();
}
}
function isArrayNode(str, arr) {
for (var i = 0; i < arr.length; i++) {
if (str == arr[i]) {
return true;
}
}
return false;
}
function lb(){
this.scripts = function(callback,includePageJs){
loadalljs(function(){
if(includePageJs){
loadFile(includePageJs,function(){
callback();
})
}else{
callback();
}
});
};
this.a = 5;
}
var library = new lb;
try.js:
function tryfunction(){
alert("try");
}
try2.js:
function try2(){
alert("try2");
}
mypage.js:
function mypagefunction(){
alert("mypagejs");
}
and im using it like this:
<script type="text/javascript" src="jsLibrary/library.js"></script>
<script>
library.scripts(function(){
tryfunction();
try2();
mypagefunction();
},"jsLibrary/mypagejs.js");
library.scripts(function(){
alert(library.a)
});
</script>
is there any way to do this with easy way? thanks for any idea or help. (Not in jquery please)
Use Requirejs
<script>
requirejs.config({
paths: {
'try1': '../path_to_your_try.js',
'try2': '../path_to_your_try2.js',
'mypage': '../path_to_your_mypage.js',
}
});
require([
'try1', 'try2', 'mypage'
], function(Try1, Try2, MyPage){
// Try1 refer to try1 file
// Try2 refer to try2 file
// MyPage refer to mypage file
});
</script>
Related
I'm trying to trigger two functions on the onclick event. They are used for tracking link from website. One is for GoogletagManager, the other one is for AdForm tracking.
I get error that the function is not defined. Any solutions to make this work?
Link
<script type="text/javascript">
function myFunction(){
secondone();
firstone();
}
function firstone() {
return console.log('first');
return gtag_report_conversion1('http://www.example.com');
}
function secondone() {
return console.log('second');
return window.adf&&adf.ClickTrack ( this,{123456},'Page Name',{});
}
</script>
<script>
function gtag_report_conversion1(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-465465465465465',
'event_callback': callback
});
return false;
}
</script>
<script type="text/javascript">
window._adftrack = Array.isArray(window._adftrack) ? window._adftrack : (window._adftrack ? [window._adftrack] : []);
window._adftrack.push({
pm: 123456,
divider: encodeURIComponent('|'),
pagename: encodeURIComponent('Page Name')
});
(function () { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://track.adform.net/serving/scripts/trackpoint/async/'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })();
</script>
After reading your edit - try moving all of the functions to the same <script></script> tag :)
I am attempting to create a tabbed form that will work across several websites. I have found that the code snippet works on some pages, and the tabs exist and function properly, but on one particular website the tabs do not display and I get the following console error: Uncaught TypeError: $(...).tabs is not a function. I have not had any luck debugging this myself or searching for answers online. Any help would be appreciated :)
Website I have issues with: http://www.jetstar.com/sg/en/home
Website it appears to work fine on: https://tigerair.com.au/
Note that the code snippet below assumes jQuery does exist on the website already. I have tried loading the latest version of jQuery first also with no luck.
if (typeof($) == 'undefined') {
var $ = jQuery;
}
function createInvisibleDiv() {
var invisiblePageSizedDiv = document.createElement("div");
invisiblePageSizedDiv.setAttribute("id", "pageDiv");
invisiblePageSizedDiv.setAttribute("class", "overlay");
document.body.appendChild(invisiblePageSizedDiv);
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.overlay{bottom:0; right:0; left: 0; top:0; overflow:hidden;background-color:rgba(88,88,90,0.8); z-index: 100; position:absolute;}';
document.body.appendChild(style);
document.body.style.position = "relative";
}
//this function creates the two tabs
function createUnorderedList(){
var $unorderedList = $("<ul></ul>");
$unorderedList.attr("id", "unorderedList");
$unorderedList.attr("class", "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all")
for (var i=1; i<3; ++i) {
var $linkItem = $("<li></li>");
$linkItem.append(createLink(i));
$linkItem.attr("class", "ui-state-default ui-corner-top")
$unorderedList.append($linkItem);
}
return $unorderedList;
}
function createLink(i){
var $link = $("<a></a>");
if (i==1) {
$link.attr({"href":'#foo', "title":"Foo"});
$link.text("Foo");
} else {
$link.attr({"href":'#bar', "title":"Bar"});
$link.text("Bar");
}
return $link;
}
function createFooForm() {
var $ele = $("<div></div>");
$ele.attr("id", "foo");
$ele.text("Thanks for looking at my code");
return $ele;
}
function createBarForm() {
var $ele = $("<div></div>");
$ele.attr("id", "bar");
$ele.text("I super appreciate it!");
return $ele;
}
function loadScript(url, callback)
{
// Adding the script tag to the head
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
var generateTabsFunction = function() {
createInvisibleDiv();
var $invisibleDiv = $('#pageDiv');
var $containerDiv = $("<div></div>");
$containerDiv.attr("id", "containerDiv");
$containerDiv.append(createUnorderedList());
$containerDiv.append(createFooForm());
$containerDiv.append(createBarForm());
$invisibleDiv.append($containerDiv);
$('body').append($containerDiv);
$( "#containerDiv" ).tabs();
}
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
}).appendTo("head");
loadScript("https://code.jquery.com/ui/1.12.1/jquery-ui.js", generateTabsFunction);
Sounds like you have included JQuery, but forgot to include JQueryUI
I have used this function for form validation. I have used this function without
$ function(document).ready(function(){.............});
Its working well. Now I want to add my code under this
$ function(document).ready(function(){.............});
How could I do that. Thanks.
function myFunction () {
var a = document.getElementById("num").value;
var b = document.getElementById("num2").value;
var msg = "";
if(a==""){
msg+="Please Fill this field.\n";
num.className = "color";
}
if(b==""){
msg+="Please Fill this field.\n";
num2.className = "color";
}
if(msg=="") {
return true;
}
else {
document.getElementById("result").innerHTML="Please fill the user name";
document.getElementById("result2").innerHTML="Please Put your E-mail";
return false;
}
}
$(document).ready(function(){ myFunction(); });
Not able to load dynamically the CDN of jquery, bootstrap, D3.js, knockout.js using jquery. i am using jquerycdn variable to pass to the loadscript() when checkjquery() is false. But when i am passing still the jquery CDN is not loading. Same issue facing with the remaining files like bootstrap, D3.js, knockout.js etc. All these file CDN's are kept in one js file.
Please check the below code:-
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
Initialize.prototype.checkJQuery = function () {
if (window.jQuery) {
return true;
} else {
return false;
}
};
if (!this.checkJQuery ()) {
console.log("jquerynot available")
this.loadJQuery ();
if (!this.checkJQuery ()) {
throw "Error loading jquery"
}
} else {
console.log("jquery available")
}
Initialize.prototype.loadJQuery = function () {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function (src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.head.appendChild(my_awesome_script);
}
You need to give jQuery time to load before checking to see that it's loaded. An onload trigger would be better than timeout, but here's your code working.
function Initialize() {
var self = this;
this.jqueryCDN = "https://code.jquery.com/jquery-1.11.3.min.js"
if (!this.checkJQuery()) {
console.log("jquery not available")
this.loadJQuery();
setTimeout(function() {
if (!self.checkJQuery()) {
throw "Error loading jquery"
} else {
alert("jQuery loaded!");
}
}, 2500);
} else {
console.log("jquery available")
}
}
Initialize.prototype.checkJQuery = function() {
if (window.jQuery) {
return true;
} else {
return false;
}
};
Initialize.prototype.loadJQuery = function() {
// var js_code = atob(this.jqueryStr);
// eval(js_code);
this.loadScript(this.jqueryCDN);
};
Initialize.prototype.loadScript = function(src) {
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src', src);
document.body.appendChild(my_awesome_script);
}
var i = new Initialize();
You might also look at this approach.
I'm writing a snippet of code to be put on any third party website and have NO idea what environment it will be dropped into. My end goal is for the badge to be
<script src="http://example.com/js/badge.js"></script>
I would like to use jQuery in my badge code to make my life easier, but I don't want to require another include on the client side (getting anything updated on the client is a pain).
This is the best I could come up with. I don't want anything before or after my script to be affected with any leftover variables or weird collisions. Does anyone see any issues?
(function() {
function main($) {
// do stuff with $
$(document.body).css("background", "black")
}
// If jQuery exists, save it
var old_jQuery = null;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery.noConflict(true);
}
}
var addLibs = function() {
// Body isn't loaded yet
if (typeof(document.body) == "undefined" || document.body === null) {
setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
document.body.appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || jQuery("*") === null) {
setTimeout(checkLibs, 100);
return;
}
var new_jQuery = jQuery.noConflict(true);
jQuery = old_jQuery;
main(new_jQuery);
}
addLibs();
})();
I ended up going with http://yourock.paulisageek.com/js/popup.js . See the test (with console logging avialable) http://paulisageek.com/tmp/jquery-programatically.html. It doesn't reset jQuery and $ until jQuery actually finishes loading. Any way to block javascript without an infinite loop (which blocks the jQuery loading itself)?
// A namespace for all the internal code
var yourock = {};
// Include JQuery programatically
(function() {
// Don't let the script run forever
var attempts = 30;
// If jQuery exists, save it and delete it to know when mine is loaded
var old_jQuery;
if (typeof(jQuery) != "undefined") {
if (typeof(jQuery.noConflict) == "function") {
old_jQuery = jQuery;
delete jQuery;
}
}
var addLibs = function() {
var head = document.getElementsByTagName("head");
if (head.length == 0) {
if (attempts-- > 0) setTimeout(addLibs, 100);
return;
}
var node = document.createElement("script");
node.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js";
head[0].appendChild(node);
checkLibs();
}
var checkLibs = function() {
// Library isn't done loading
if (typeof(jQuery) == "undefined" || typeof(jQuery) != "function" || jQuery("*") === null) {
if (attempts-- > 0) setTimeout(checkLibs, 100);
return;
}
yourock.jQuery = jQuery.noConflict(true);
if (typeof old_jQuery == "undefined")
jQuery = old_jQuery;
}
addLibs();
})();
This works:
(function(){
if (window.jQuery !== undefined) {
doStuff(jQuery);
} else {
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
var interval = setInterval(function(){
if (window.jQuery) {
clearInterval(interval);
var JQ = jQuery.noConflict(true);
doStuff(JQ);
}
}, 100);
}
})();
function doStuff($) { /* Do stuff with $ */ }
Including jQuery again will override the $ variable, which might be an older version of jQuery or another framework. You should probably save that too.
I don't have tested so much this code but it should work...
(function($, window) {
var version = ($ && typeof($) == 'function' && $().jquery ? ($().jquery).split('.').join('') : 0), // 1.8.1 -> 181
jBack = null;
if (version) console.log('jQuery current version : ', version);
else console.log('no jQuery');
var loaded = function() {
console.log('loaded()');
var $ = jQuery.noConflict(true); // LOCAL own jQuery version
if (jBack) {
window.$ = jBack; // Reassign ex-jQuery
window.jQuery = jBack;
}
// OK : now work with OUR new $
console.log('jQuery new version : ', $().jquery);
},
loadJs = function(jsPath) {
console.log('loadJs()');
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', jsPath);
s.onload = loaded;
document.getElementsByTagName('body')[0].appendChild(s);
};
if (version) jBack = $;
if (version < 180) loadJs('http://code.jquery.com/jquery-1.9.1.min.js');
else loaded();
})((typeof(jQuery) == 'function' ? jQuery : null), window);