Check is external Javascript has changed or not - javascript

Here is my code which might not be the best solution of my problem, and my goal is to check the external script (script.js) every 2 seconds if it's code has changed. If it is changed, then execute it.
function connectLoader(retval) {
console.log('Executing...');
var old = document.getElementById("EPMagic");
if (old !== null) {
old.outerHTML = "";
delete old;
}
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','EPMagic');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.com/script.js');
head.appendChild(script);
}
setInterval('connectLoader()',2000);
The problem is that /script.js is still executed even if it is not being changed.
The code on /script.js is simply alert('Execute');

Use setAttribue to set the attributes values:
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.setAttribute('id','loadScript');
script.setAttribute('type','text/javascript');
script.setAttribute('src','http://server.ip/script.js');
head.appendChild(script);

Related

load javascript files from folder

I am not sure what is the best approach to load all .js files from a folder from within index.html
The number of .js files will change so I cannot define them in the index.html the usual way. I cannot use php or jQuery solutions which would make it easier.
<script>
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "page-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext();
</script>
You can load a new JS file by creating a new <script> tag.
var filename = "JSDir/JSFile.js";
var newScript = document.createElement("script"); ///Create a new <script> element
newScript.setAttribute("type", "text/javascript"); // Set type to JS
newScript.setAttribute("src", filename); //Set src, your file to load
document.getElementsByTagName("head")[0].appendChild(newScript) //Append this script tag to the end of your head element
If you know your JS files are going to be named basename-1.js you can set a callback so that onload you increment to the next fielname basename-2.js 3, 4... and when the final one fails to load it will stop trying to load further.
var count = 1;
function LoadNext()
{
var newScript = document.createElement("script");
newScript.setAttribute("type", "text/javascript");
newScript.setAttribute("src", "basename-" + count++ + ".js"); //Increment the counter so we get the next page each time
newScript.onload = LoadNext; //When the script loads call this function again
document.getElementsByTagName("head")[0].appendChild(newScript)
}
LoadNext(); //Load basename-1.js
^^Not tested, but if that way of checking the file exists fails. You can always use AJAX and check for 404

How do I add a javascript alert to innerHTML at runtime

When a particular event happens that I listen out for - I want to populate the div 'divDynamicAdvert` with the javascript that calls my Google Ad code.
Huge thanks to "tenbits" for showing me that I need to be appending a script node like this:
function myEventHandler(evt) //called when event is caught
{
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
}
This works great, but in place of the alert, I need to insert the Google Ads Javascript:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3286208413631803";
/* Standard MPU */
google_ad_slot = "8630273973";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
I've tried:
var script = document.createElement('script');
script.textContent = 'google_ad_client = 'ca-pub-3286208413631803'; google_ad_slot = '8630273973'; google_ad_width = 300; google_ad_height = 250;';
document.getElementById('divDynamicAdvert').appendChild(script);
var script = document.createElement('script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"');
document.getElementById('divDynamicAdvert').appendChild(script);
I've tried escaping the slashes too, but no luck... Can you guys help?
As #slebetman already said, innerHTML wont work. If you trying to evaluate script via DOM, and not eval(code), etc - do this with SCRIPT Node:
var script = document.createElement('script');
script.textContent = 'alert(1)';
document.getElementById('divDynamicAdvert').appendChild(script);
// actually it doesnt matter where you append it
EDIT:
In any case create a SCRIPT NODE, and then manipulate with it - add a script content to it OR add src attribute if you reference external source
var script;
// content
script = document.createElement('script')
script.textContent = 'alert(1)'
document.body.appendChild(script);
// google api source
script = document.createElement('script');
script.src = 'ANY_URL';
// -> in this case, same as script.setAttribute('src', 'ANY_URL');
document.body.appendChild(script);
Having some further questions, do not hesitate to ask in comments.

JavaScript synchronization

I don't know how I can synchronize next code:
javascript: (function() {
var s2 = document.createElement('script');
s2.src = 'http://192.168.0.100/jquery.js';
document.body.appendChild(s2);
s = document.createElement('link');
s.rel = "stylesheet";
s.href = "http://192.168.0.100/1.css";
s.type = "text/css";
document.body.appendChild(s);
})();
//var startTime = new Date().getTime();
//while (new Date().getTime() < startTime + 1000);
$(document).ready(function(){
b="c:\\1.txt";
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile(b, true);
f1.WriteLine("Testing") ;
document.writeln("File " + b + " is created.");
});
When I run this script at first I get an error SCRIPT5009: '$' is undefined. I think that is because jQuery library is yet no loaded. When I try to run the same script after error's appearencing - it behavior is corect. For synchonization I try to use code that is commented in upper listing. Is works (not always). But I understand that is no strict synchronization (it dependet of concrete situation). How can I use more clever synchronization?
(function($){
//use $ now
$(function(){
//dom ready
});
})(jQuery);
Be sure to load this libary in the footer below the jquery library.
This is due to the fact that putting in the script tag via appendChild dhtml method makes it evaluate async. To listen for it getting 'ready' as youre doing it on the document - follow this pattern
(function() {
var s2 = document.createElement('script');
s2.src = 'http://192.168.0.100/jquery.js';
document.body.appendChild(s2);
s2.onload = s2.onreadystatechange = function(){
if(s2.readyState == "complete") $(document).ready(function(){
b="c:\\1.txt";
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile(b, true);
f1.WriteLine("Testing") ;
document.writeln("File " + b + " is created.");
});
}
s = document.createElement('link');
s.rel = "stylesheet";
s.href = "http://192.168.0.100/1.css";
s.type = "text/css";
document.body.appendChild(s);
})();
The issue is that the line with the $ is being hit when the script tag has been added but before the file has been downloaded. Normally browsers block while loading JavaScript which prevents this issue, but since you're doing it programatically you don't get the standard synchrony.
Your best bet would be to wait for the script to be loaded. There's information here:
Dynamic, cross-browser script loading
On catching the load event for the completion of the script download. You can then call your existing $ ready function as a callback to that event. I'd suggest using a loader that is made for this stuff, or just use a standard script tag in the DOM unless you have a compelling reason not to.

How do dynamically ad div with <script>tag including inline JS so that this JS executes?

I am having an issue trying to dynamically add and execute a div containing inline Javascript?
var div = document.createElement('DIV');
div.onready = (function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);
where wallpaper_ads.custom[i] contains a string, e.g. 'BMX_wallpaper_2328x1080_homepage'.
Above code does not work. But it works if I change GA_vitalFillSlot() to alert():
var div = document.createElement('DIV');
div.onready = (function(name) { return alert(name); })(wallpaper_ads.custom[i]);
document.getElementById('wallpaperAdContainer').appendChild(div);
Also, doing something like this doesn't work either:
var js = document.createElement('SCRIPT');
js.type = 'text/javascript';
js.innerHTML = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';
document.getElementById('wallpaperAdContainer').appendChild(js);
Any ideas what is wrong here?
Either:
js.src = 'myCode.js';
or
js.text = 'alert("hey");';
Script inserted using innerHTML does not get executed.
This line of code:
(function(name) { return GA_vitalFillSlot(name); })(wallpaper_ads.custom[i]);
is executing immediately setting the div.onready equal to the result of GA_vitalFillSlot(name). Change it so the onready points to a function:
div.onready = (function(name) {
return function() {
GA_vitalFillSlot(name);
};
})(wallpaper_ads.custom[i]);
This should work
js.src = 'GA_vitalFillSlot("'+wallpaper_ads.custom[i]+'");';

Changing innerHTML of script tags in IE for loading google plusone button explicitly

To add Google's plusone button on your website the following script tag is to be inserted (for explicit load).
<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
{"parsetags": "explicit"}
</script>
It looks pretty straight forward in HTML. However I wan't to insert the script using a JS file. So I use the following code:
var e = document.createElement('script');
e.src = "https://apis.google.com/js/plusone.js";
e.id = "googplusonescript";
e.innerHTML = '{"parsetags": "explicit"}';
document.getElementsByTagName("head")[0].appendChild(e);
It works pretty awesome in all the browsers except IE because IE doesn't allow us to write the innerHTML of script tags. Anywork arounds anyone ? (I have jquery inserted in the page. So can use jquery too.)
Came across the same issue.
Under IE you should use
script.text = '{"parsetags": "explicit"}';
instead of script.innerHTML
try creating a textNode and appending it to your script tags:
var myText = document.createTextNode('{"parsetags": "explicit"}');
myScriptTag.appendChild(myText);
Try the following:
window['___gcfg'] = { parsetags: 'explicit' };
var ispoloaded;
function showpo() {
var pohd = document.getElementsByTagName('head')[0];
var poscr = document.createElement('script');
poscr.type ='text/javascript';
poscr.async = true;
poscr.text ='{"parsetags": "explicit"}'; //works on IE too
poscr.src = "http://apis.google.com/js/plusone.js";
pohd.appendChild(poscr);
ispoloaded = setInterval(function () {
//check if plusone.js is loaded
if(typeof gapi == 'object') {
//break the checking interval if loaded
clearInterval(ispoloaded);
//render the button, if passed id does not exists it renders all plus one buttons on page
gapi.plusone.go("idthatexists");
}
}, 100); //checks every 0.1 second
}

Categories

Resources