mootools asset not loading - javascript

I'm trying to dynamically trigger a Google adwords conversion in a situation where the "success" page is the same page as the form page (reposts to the same page and sets a message). So I set the message and check for it with javascript, which then should load the adwords conversion js. Here's the code:
<script type="text/javascript">
//<![CDATA[
window.addEvent('domready', function() {
var convmessage = null;
convmessage = $('message');
if(!!convmessage) {
console.log("yo");
if ($('message').getChildren()[1].innerText){
console.log("yoyo");
var google_conversion_id = 1234;
var google_conversion_language = "en-US";
var google_conversion_format = "1";
var google_conversion_color = "ffffff";
var google_conversion_label = "Label";
var myScript = Asset.javascript('http://www.googleadservices.com/pagead/conversion.js', {
id: 'myScript',
onLoad: function(){
console.log("loaded");
}
});
}
}
});
//]]>
</script>
When I submit the form, my console log reads
yo
yoyo
but never displays the loaded message. So it appears that the script should get loaded but never does, even though the script (apparently) executes properly.
Is there something I'm missing about using the mootools asset function, or another reason that the script doesn't get loaded?
Thanks

I was just checking this function on JS Fiddle, and It worked fine for me. Just not with your script.
It looks like Google is force downloading the script, which it looks like breaks the mootools script. I would try hosting that script on your own server or use another one.
You can see what I did here:
http://jsfiddle.net/9h8Zx/1/

Related

Cookiebot Cookie Consent Script

I am adding ZohosalesIQ to the CookieBot Prior Consent widget on w WP install.
This script given by zoho is
<script type="text/javascript" data-cookieconsent="statistics">
var $zoho = [];
var $zoho = $zoho || {};
$zoho.salesiq = $zoho.salesiq || {
widgetcode: "1c636a8a8d8e3410b7e579760898b7768f3cb213adb21970788a3891735df801800b6e4a1385c37b0f792b9ee54ce",
values: {},
ready: function() {}
};
var d = document;
s = d.createElement("script");
s.type = "text/javascript";
s.id = "zsiqscript";
s.defer = true;
s.src = "https://salesiq.zoho.eu/widget";
t = d.getElementsByTagName("script")[0];
t.parentNode.insertBefore(s, t);
d.write("<div id='zsiqwidget'></div>");
</script>
I am supposed to be adding <script type="text/plain" data-cookieconsent="statistics">
to the script tag to enable prior consent on cookies created by this script however, when I add this it breaks and fails to load.
Console is empty but the page renders as a white page after pre-load. When I add the code with the jaavscript type tag, it works fine.
I've tried popping itto a call back function but no joy :(
Any pointers would be great.
If the script tag is using the deprecated JavaScript function “document.write” it might cause the problem you have described above because using this function the script is loaded synchronously and it will then clear the window content (generates blank page).
To prevent this issue please make sure that the script is loaded asynchronously since the Cookiebot triggers all scripts asynchronously (i.e. to wait for the visitor’s consent) in order to work properly.
You need rewrite it to use a different approach e.g. “document.write = function(node) {document.body.insertAdjacentHTML(‘beforeend’, node);}”

Loading External JS Files After Mouse Move or 5 Seconds Later for Better Page Speed Optimization

I am using smartsupp live chat script for my website. It is good however it dramatically increases my page loading time.
According to gtmetrix.com, my normal page load details:
Fully Loaded Time
2.6s
Total Page Size
751KB
Requests
42
But when I add this script:
Fully Loaded Time
20.6s
Total Page Size
2.00MB
Requests
66
So, I want to use this script but I don't want to load it firstly. I want to load it when visitors mouse move or 3-5 seconds later.
Do you have any solution for this? Thank you.
Default smartsupp codes like this:
<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;c.defer=true;
c.src='//www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
</script>
EDIT:
I think this is not related with my question but I think this is another side of this problem too. According to gtmetrix.com I have "Leverage browser caching" problem beacuse of this script too. They said:
Leverage browser caching for the following cacheable resources:
https://s2.smartlook.com/rec/check (expiration not specified)
https://s2.smartlook.com/rec/init (expiration not specified)
https://s2.smartlook.com/rec/tag (expiration not specified)
https://static.smartsupp.co/chats/112939/avatar-gasqccul5z.png (expiration not specified)
https://rec-src.smartlook.com/recorder.js (5 minutes)
https://www.google-analytics.com/analytics.js (2 hours)
Maybe you can find a good solution for all of these problems. Thank you very much again.
Unfortunately other solutions are not fit for my problem. So I found a code like this:
<script>
window.onload = function(){
setTimeout(loadAfterTime, 5000)
};
function loadAfterTime() {
// your code here
}
</script>
And used it like:
<script>
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.onload = function(){
setTimeout(loadAfterTime, 5000)
};
function loadAfterTime() {
window.smartsupp||(function(d) {
var s,c,o=smartsupp=function(){ o._.push(arguments)};o._=[];
s=d.getElementsByTagName('script')[0];c=d.createElement('script');
c.type='text/javascript';c.charset='utf-8';c.async=true;
c.src='//www.smartsuppchat.com/loader.js?';s.parentNode.insertBefore(c,s);
})(document);
}
</script>
After that, gtmetrix.com results:
Fully Loaded Time
2.7s
Total Page Size
650KB
Requests
34
So, it works! I recommend this solutions for all webmasters.
You can use javascript onload native method or document.ready from jquery library.
It is hard to accept that those loading time will be same or more or less same all the time, since it depends on internet speed and server capability.Instead of depending on setTimeout you can rely on window.onload
window.onload fires when the resource has loaded.
window.onload = function() {
// script for Smartsupp Live Chat
};
Its easy to do achieve this with jQuery. You just need to get the external js file after the document is ready and apply a set timeout function for your external script.
<script>
$(document).ready(function() {
setTimeout(function() {
var _smartsupp = _smartsupp || {};
_smartsupp.key = 'mykeynumber';
window.smartsupp || (function(d) {
var s, c, o = smartsupp = function() {
o._.push(arguments)
};
o._ = [];
s = d.getElementsByTagName('script')[0];
c = d.createElement('script');
c.type = 'text/javascript';
c.charset = 'utf-8';
c.async = true;
c.defer = true;
c.src = '//www.smartsuppchat.com/loader.js?';
s.parentNode.insertBefore(c, s);
})(document);
console.log("External js file loaded");
}, 5 * 1000) //calls the external chat after 5 seconds
});
</script>
Edit #1
Leverage browser caching doesn't works on external resources :)

how to know if the javascript, which has been loaded by a javascript, has been loaded [duplicate]

This question already has answers here:
'onload' handler for 'script' tag in internet explorer
(2 answers)
Closed 7 years ago.
I know my subject is quite tricky but i dont know how to much more ellaborate it on the subject alone.
so here how it goes.
i have a button
Load IT!
on the script tag:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
alert("done! the file has been loaded");
}
the script well, when loaded will automatically have a modal box.
but the problem is, my alert seems to fire first than what is one the script
so how will i know if i have finished to load the script?
update for the first attempt to answer:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
$(document).ready(function() {
alert("done! the file has been loaded")};
}
same problem
alert does indeed run before the script has been loaded. All that appending the script tag to the page does is append the script tag to the page. Then the browser has to download the script and, once received, run it. That will be after your loadTheFile function has exited.
So you need to get a callback when the script has actually be loaded and run. This is more standard than it used to be, but still has some cross-browser hassles. Fortunately for you, jQuery's already solved this problem for you (since you're using jQuery already):
function loadTheFile() {
$.getScript('http://www.thisismyexternalloadingjsfile"')
.then(function() {
alert("done! the file has been loaded");
});
}
Re your comment:
but my script file has data-* attributes
Assuming you're talking about data-* attributes on the script tag, then you'll have to do a bit more work, but it's still fairly straightfoward:
function loadTheFile() {
var load = $.Deferred();
var script = document.createElement('script');
script.src = 'http://www.thisismyexternalloadingjsfile"';
// No need for `type`, JavaScript is the default
script.setAttribute("data-foo", "bar");
script.onreadystatechange = function() {
if (script.readyState === "loaded") {
load.resolve();
}
};
script.onload = function() {
load.resolve();
};
load.then(function() {
alert("done! the file has been loaded");
});
document.body.appendChild(script); ;// Or wherever you want to put it
}
The onreadystatechange bit is to handle older versions of IE.
Rather than forge the script with text and jQuery, just use native Javascript:
var s = document.createElement('script');
s.onload = scriptLoaded;
s.src = '/path/to/my.js';
document.body.appendChild(s);
function scriptLoaded() {
console.log('Script is loaded');
}
Try something along these lines:
Your main page:
function whenScriptIsReady(){
alert('This function is called when the other script is loaded in!')
}
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','myotherjs.js');
$('body').append(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Load IT!
myotherjs.js:
alert('This will automatically run when the JS is loaded in!');
whenScriptIsReady();
JavaScript is executed asynchronously, so you alert will be executed before the browser can load the new script. If you want to execute logic after the script has been loaded, you could add an event listener to your script that will call the function 'loadFunc` once the script load is completed:
var loadFunc = function() {
alert("External Javascript File has been loaded");
};
//Other browsers trigger this one
if (script.addEventListener)
script.addEventListener('load', loadFunc, false);

How to conditionally include assets in the <head> with Angular

I am building a one-page Angular app. One of the views has content which depends on an external javascript library.
I don't want to include this external JS resource on every view of the site, just the single view which depends on it.
What is the best way to conditionally include blocks of code based on the current view?
If it's possible I'm hoping I can place in the something like this:
<script ng-if="view == 'view1'" type='text/javascript' src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
So you should include the library script in page.
Then within directive bound to elements it needs to act on do the initialization.
app.directive('unity', function () {
return {
link: function (scope, element, attrs) {
// element is jQuery object when jQuery.js is included in page
// before angular - or it is a jQLite object similar to a jQuery object
// config code
u.initPlugin(element[0], "web_ovar_beta.unity3d");
}
}
});
Usage in view:
<div unity></div>
This can easily be expanded to pass in attributes to the directive from controller
It is
<script ng-if="view == 'view1'" type='text/javascript' ng-src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
And it is something that you don't want to do. It doesn't guarantee that the script won't be loaded twice. Since the script is being used for particular view, make it one-time resolving service
app.factory('unityResolver', function ($document, $rootScope, $q, $timeout) {
var deferred = $q.defer();
var script = angular.element('<script>')[0];
script.src = '...';
script.async = true;
script.onload = script.onreadystatechange = function () {
if (['loaded', 'complete', undefined].indexOf(script.readyState) < 0)
return;
script.onload = script.onreadystatechange = null;
deferred.resolve();
$rootScope.$apply();
}
script.onerror = function onerror() {
script.onerror = null;
deferred.reject();
$rootScope.$apply();
};
$timeout(onerror, 20000);
$document.find('head').append(script);
return deferred.promise;
});
and use it in view/route resolve.
What your wanting to in turn is impossible.
You can get Javascript to include a javascript file if you want however if your using AJAX to load the content that is needed leave it in there it would be the same amount of time to load anyway. but once a file has been loaded into JavaScript it finished with you can remove the file from your HTML but the JavaScript engine still has the content of that file loaded in to it.
Try it in your browsers(chrome or FF with Firebug) inspector now:
open a new tab and go to about:blank then put the code below into the console
var include = (function(){
// the reference to the script
var theScript;
return function (filename, status){
if(status == 'on'){
// adding a script tag
var head = document.getElementsByTagName('head')[0];
theScript= document.createElement('script');
theScript.src = filename;
theScript.type = "text/javascript";
head.appendChild( theScript )
}else{
// removing it again
theScript.parentNode.removeChild( theScript );
}
}
})();
taken from Remove specific <script> tag in <head> tag by onclick event
then in your inspector's console
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'on')
now check Elements and you will see jQuery loaded in the pages head tag.
and type jQueryinto console and you will see function (a,b){return new n.fn.init(a,b)}
And then use this into your console
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'off')
and check your elements tab again the script tag will have gone.
however go back to console and type jQuery again and you will see function (a,b){return new n.fn.init(a,b)} as even though you have unloaded the file you can't remove the executed code from memory.
You have 2 options another framework page gets loaded into an iFrame or if you want to use Anagular to load the View in then just include the file in your head there is no point not having and then removing it as once it is loaded it's loaded

How to set a timeout for loading a external javascript file which is down

Im using javascript to include some content served up from a php file on another server. However, this other service can sometimes get flaky and either take a long time to load or will not load at all.
Is there a way in JS to try to get the external data for x number of seconds before failing and stopping to include js.
If you mean
<script src="javascript.php"></script>
then the short answer is no which is why JSONP is not useful in these cases.
The longer answer is that you might be able to use setTimeout and test a variable you KNOW should be in the javascript and give an error if the var/function is not there.
If you do
<script>
var start = new Date();
var tId;
function testFunction() {
var end = new Date();
if ( (end.getTime()-start.getTime()) > 10000) {
alert('gave up')
}
else if (someFunction) { // someFuntion in the external JS
someFunction()
}
else tId=setTimeout(testFunction,1000)
}
</script>
<script src="javascript.php"></script>
<script type="text/javascript">
var jsLoaded = false;
setTimeout("callback()", 2000);
function callback() {
if (!jsLoaded) {
alert("Javascript not loaded after 2 seconds!");
} else {
alert('Loaded');
}
}
</script>
<script type="text/javascript" id="foo" src="url.js" onload="jsLoaded=true"></script>
Now, good luck to find what to do in order to stop loading the script.. I've tried to remove the <script> element from the DOM but it's still try to load...
If you .js is hosted on the same domain, I suggest you to use AJAX method to load the javascript (see http://codesnippets.joyent.com/posts/show/602)

Categories

Resources