I have a js function that should get some advertisement js code from some server and place it in specified DOM element. It looks like this:
function LoadAd(scriptContainer)
{
var js = document.createElement("script");
js.async = true;
js.src ='someAdUrl';
var sHolder = document.getElementById(scriptContainer);
if (sHolder != null) {
sHolder.appendChild(js);
}
}
the argument 'scriptContainer' is an ID of DOM element, that should contain created js element.
This external js file contains a lot of code that should provide an ad. But this code is never reached and never executed.
When I put this js src directly in html:
<script src='someAdUrl'></script>
it works fine.
I've checked, the js file is being loaded.
Any ideas?
EDIT: Here is an example of content of js file:
document.write('<!-- Some Message -->\n\n\n<img width=\"336\" height=\"110\" border=\"0\" src="someImageSource">\n\n');
And it always contains document.write
If the external JS file is being loaded, have you checked whether or not the function is actually being invoked and run?
If the function isn't self-executing and you don't explicitly call it, the code won't run.
I use this code in my case. It may help you
var js=document.createElement('script');
js.setAttribute('src','http://domain.com/js/jscpt.js');
document.body.appendChild(js);
Related
Hello I have a problem with JavaScript function.
I have 3 external JS files that are included to my JS file like that:
var badgeJs = document.createElement('script');
badgeJs.type = 'text/javascript';
badgeJs.src = 'url'
document.head.appendChild(badgeJs);
So here is the problem I need to use 3 functions, but sometimes I received error
Refference error: functionName is not defined, after that I refresh the page and first function works but second one no, and every time on refresh some of functions are not defined.
I don't know what is the problem and why this happen? Any advice will be appreciate.
I don't know if this is gonna help but JS code is for a shopify-app
How I call functions
var content = 'function1(param);function2(param1, param2, param3, [10, 25]);function3(param1, param2);';
(function() { var script = document.createElement('script'); script.text = content; var body = document.querySelector('body'); body.append(script);})();
Your file inclusions run at the sime time you're trying to call your functions. As the file inclusion need time to load your files, you are calling the functions before they have been loaded.
You have to manually add your scripts to the HTML:
<script type="text/javascript" src="/to/your/file.js">
And then run your function when the DOM has been loaded:
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
});
If you can't change the HTML, then include your files dynamically and make sure to call your functions when the files are loaded.
I have been using XMLHttpRequest to load my javascript file and insert it into the the head of my html file. I have tried:
var headNode = document.getElementsByTagName('head')[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = this.url.replace(project.basePath,'');
headNode.appendChild(js);
This works but i have a timing problem when i do it this way, so no function can be called. I am now trying another way, where i can get the string of codes from the js file and insert it into the head, when i do it this way it clears my html and only adds the new code in.
var code= this.ajaxRequest.responseText;
script.write('<script>'+code+'</script>')
is there away to append it to the head for example (this doesn't work);
var code= this.ajaxRequest.responseText;
var headNode = document.getElementsByTagName('head')[0];
var script = document.createElement("script");
script.write('<script>'+code+'</script>')
headNode.append(script)
Thanks for the help in advance. p.s I am not using jquery.
The first approach you tried failed because XmlHttpRequest (also called an ajax request) is asynchronous.
So by the time your script gets loaded, your other scrip tags code get executed (before the script file is load).
You could fix this issue, by using event handling in javascript.
You can create a custom event called 'loaded' and dispatch it.
And in your other script tag that contains code, add an event listener for the same event.
And in the event handling or the event listener function, call the required functions that you want to execute after the script gets loaded.
Your second approach fails because document.write or document.append over-writes the document if it is used after the html page is rendered.
So using this functions after the page has displayed should be avoided.
P.S - Sorry that I could not give any demo code as I am answering this from my cell phone.
JS parser error on your < /script> in code.
try
var code= this.ajaxRequest.responseText;
script.write('<script>'+code+'</scr'+'ipt>');
Can you just eval() the response text?
I know that I can run an external Javascript file from within HTML with the following syntax:
<script type="text/javascript"
src="http://somesite.com/location/of/javascript.js">
</script>
This will result in http://somesite.com/location/of/javascript.js being run the moment the browser reads that line of the HTML.
But is there a way I can run an external Javascript file from within Javascript? Something like:
if (x == 1)
{
run this! -> http://somesite.com/location/of/javascript.js;
}
Obviously that's not valid code. But I can't find any example of what might be the right way to do this (if it exists), because all the help text I find with Google searches tell me how to run Javascript from within HTML
I know that I can include a Javascript file and then call functions within it. However, in this situation, I do not have any control over http://somesite.com/location/of/javascript.js, and it is designed to execute the moment it is called. I can't change how it works, so I need to figure out how to call it at the right time in the right way.
Is there a way I can get it to be called and executed immediately depending on a conditional statement?
Yes, in Pure Javascript you can Load javascript dynamically
var s = document.createElement("script");
s.src = "test.js";
document.body.appendChild(s);
There is a way...
var extfile = document.createElement('script')
extfile.setAttribute("type","text/javascript")
extfile.setAttribute("src", external_jsfilename)
document.getElementsByTagName("head")[0].appendChild(extfile)
Simple as that ....
Use jQuery's .getScript() the file will be loaded and then executed
if (x == 1)
{
$.getScript( "http://somesite.com/location/of/javascript.js");
}
I am downloading the JS file asynchronously by appending the JS file to HTML head.
Now in html body, before using the JS file, I want to check if JS file has downloaded and is present in the cache.
If the JS file is NOT present in the cache(e.g: in case of slow internet connnections), I want to block until it is downloaded.
In other words, if JS download is not complete, i want to simulate the behavior as in the case of blocking JS download.
Any idea how this can be achieved?
you can instantiate any object in JS file and in the HTML file you can check if that object is available using typeOf operator so if typeof(x) is undefined you can assume that file is not yet downloaded
Get the JS synchronously instead. Just append a script tag to html > head with src="<script-location>" and the browser will do this download synchronously.
going on a tanget here:
It is poor user-experience to block until something has downloaded. If you write your code using principles of graceful degradation, your page should only activate functionality that is available. Would you let another web-developer subject you to this. No I wouldn't - I would close that tab and move on :)
If you have control over the HTMl file and the JS file: define a "callback" function somewhere in the already-loaded code, and call it from the end of your JS file. Example function:
<html>
<head>
<script>
function notify_file_is_loaded(identifier) {
if (identifier === 'somefile.js') {
// it's loaded!
// run the code that (in synchronous mode) you'd block for
}
}
</script>
<!--- ... --->
and the JS file:
// somefile.js
// some JS code goes here
// ...snip...
notify_file_is_loaded('somefile.js');
Are you deferring the loading of the JavaScript file via JavaScript? If so you should be able to use the onload event handler to execute your code after the JavaScript file has been loaded:
<script>
var js = document.createElement('script');
js.onload = function() {
// your code goes in here
}
js.src = 'foo.js';
document.body.appendChild(js);
</script>
I have this in a test.html:
<script>
function h(){
g();
}
<script>
k.js has:
g();
In test.html I successfully entered h() but not g(). I added k.js as a script tag:
scriptTag.src="k.js"
It is not finding g() just the same.
What am I doing wrong?
You said that k.js has this:
g();
This isn't a valid function to call, it's just trying to call g(); which still isn't defined.
What k.js should have is something like this:
function g() { alert('you called g()'); }
It sounds like you are trying to add the script when the document loads or whenever an event fires. If you try to call a function immediately after the external file that contains it is added to the dom, you will get an error. The external file will not have been downloaded. There is latencey in this process. The computer cycles through the client side script faster than it can dowload the .js file. Ad a set timeout and you should see it working. I could be wrong but that is my thoughs...
Have you ensured that k.js is loaded before calling h()?
Is it successfully finding k.js and the path resolves correctly?
Make sure the function you are calling is higher up in the DOM than the line calling it.
I added k.js as a script tag [ scriptTag.src="k.js" ]
Sounds like you're writing your script tag dynamically? If so, make sure you're injecting it into the DOM then waiting for the browser to load it before you try and access anything from it. Just creating the script node won't do anything until you inject it somewhere.
Does your code look someyhing like this?
var scriptTag = document.createElement('script');
scriptTag.src = 'k.js';
Really, you ought to have this line:
scriptTag.type = 'text/javascript';
And as previously mentioned, the script has to be inserted into the DOM. These two lines should solve the problem:
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
resulting in:
var scriptTag = document.createElement('script');
scriptTag.src = 'k.js';
scriptTag.type = 'text/javascript';
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);
Now why aren't you using this?
<script type="text/javascript" src="k.js" />