Trouble loading js - javascript

I'm sorry in advance if this is simple or if it just can't be done. Basically, I am trying to load an age verification js on my site, but I am trying to chose between different pages depending on the legal drinking age in different countries.
If I load the script simply, it works fine:
<script type="text/javascript" src="https://av.ageverify.co/jsfr/singlemalt.18.js"></script>
However, if I trying to do any sort of modification to this script, it won't load at all. For example, if I try to set the src to a variable (that I would call in a different script, it fails to load).
<script>
url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
</script>
<script type="text/javascript" src=url></script>
Any ideas would be greatly appreciated!
EDITED:
Additional info:
I tried to use getScript as people have suggested but also had issues with it:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
$.getScript("https://av.ageverify.co/jsfr/singlemalt.18.js");
</script>
or this method:
function loadJs() {
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
This last one seems to work with other simple scripts, but maybe this particular script is looking for some sort of browser condition? Any suggestions on how to figure that out or what to look for? There should be an age verification page that pops up, asking your age.

HTML tags do not understand variables. You need to use a URL for the src attribute. HTML has no idea what your JavaScript variables are.
If you want to load the .js file this way, you need to use JavaScript. What you can do is create a new <script> tag then append it to the page.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
If you are using jQuery, this is basically what $.getScript does.
var url = "https://av.ageverify.co/jsfr/singlemalt.18.js";
$.getScript(url);

Related

Creating new instances of external script in React

I've been stuck with integrating external script in my React application.
The idea is to use external html/js widget that will suggest addresses based on the data in the input field.
The widget requires two things:
<script type="text/javascript" src="https://some.address.com/widget.min.js"></script> - must be inside the html head tag.
<script> var widget = new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});</script> - must be inside the html body tag.
My question is - how can I create new instance of an external script if the given item is not imported as a module? I know that the first part can be resolved with useEffect hook. However, if I try to make new instance of jsWidget, the code editor throws an error saying that jsWidget is not defined.
The given widget works fine in pure html. For example:
<html>
<head>
<script1></script1>
</head>
<body>
<script2></script2>
</body>
</html>
I've been stuck with this for a long time now and I can't figure out a way how to fix this. I would be really thankful if someone could give some advice.
maybe not the best method. i think it'll works
var script1 = document.createElement("script");
script1.type = "text/javascript";
script1.src = "https://some.address.com/widget.min.js";
var script2 = document.createElement("script");
script2.innerHTML = 'new jsWidget ({"detail1":"foo","detail2":"bar","lang":"en"});';
document.head.appendChild(script1);
script1.onload = function () {
document.body.appendChild(script2);
};

Use a JavaScript variable inside src of script tag

Google provides its script embed code to display a trends Map by placing this code in our site.
<script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>
The above code displays the trends map.
Notice the q=iphone in the above URL. I want to pass a JavaScript variable value instead of hard coding a fixed value like iPhone in this case.
How can I use a JavaScript variable inside the src of script tag?
I tried creating script programmatically, it injects the script code but the script does not get executed.
My try
document.body.appendChild(document.createElement('script')).src= varHavingScriptURL;
My try is in a JS Fiddle here.
The problem is, you can not do this after page load. Look at the source of the script
document.write('<iframe width="500" ... </iframe>');
So you need to do this as the page is rendering because of the document.write.
Now looking at what you did
document.body.appendChild(document.createElement('script')).src = varHavingScriptURL;
That is not going to work, you need to break it up
var scr = document.createElement('script');
scr.src = varHavingScriptURL;
document.getElementsByTagName("head")[0].appendChild(scr);
but again, it is not going to work because of the document.write.
Finally after hours of struggle, I found the solution using PostScribe.
// jQuery used as an example of delaying until load.
$(function
() {
// Build url params and make the ad call
var str= "magic";
postscribe('#ad', '<script src=//www.google.com.pk/trends/embed.js?hl=en-US&q='+str+'&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330><\/script>');
});
Postscribe
Working Demo

Detect whether external script has loaded

Using JavaScript, is there a way to detect whether or not an external script (from a third-party vendor) has completely loaded?
The script in question is used to pull in and embed the markup for a list of jobs and, unfortunately, doesn't make use of any variables or functions. It uses document.write to output all of the content that gets embedded in my page.
Ideally, I'd like to display some kind of loading message while I'm waiting for the external script to load, and if it fails to load, display a "We're sorry, check back later..." message.
I'm using jQuery on the site, but this external script is called before I make the jQuery call.
Here's what the document.write stuff from the external script looks like:
document.write('<div class="jt_job_list">');
document.write("
<div class=\"jt_job jt_row2\">
<div class=\"jt_job_position\">
Position Title
</div>
<div class=\"jt_job_location\">City, State</div>
<div class=\"jt_job_company\">Job Company Name</div>
</div>
");
Attach an function to the load event:
<script type="text/javascript" src="whatever.js" onload ="SomeFunction()" />
As far as your loading... problem goes, try displaying a div for loading and then just display:none-ing it in your onload function. Make sure to handle cases where your script fails to load too, though.
Script tags block downloads, so as long as the content dependent on your script is below where your script it loaded, you should be fine. This is true even if the script is in-line in the body of your page.
This website has a great example of how this works.
This obviously does not work if you're loading the scripts asynchronously.
Scripts without async or defer attributes are fetched and executed immediately, before the browser continues to parse the page.
Source: MDN
You could put a script block after it on the page:
<script src="external_script.js"></script>
<script type="text/javascript">
ExternalScriptHasLoaded();
</script>
Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
if ($('.jt_job_list').length === 0){
$('#job-board').html("<p>We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.</p>");
};
});
Pretty simple, but I'm looking to see if an element with the .jt_job_list class is in the dom. If it isn't, I display an error message.
This worked for me: it does however, rely on the newer querySelector interface which most modern browsers support. But if you're using really old browsers, you can use getElement... and run a for loop.
function loadJS(file, callback, error, type) {
var _file = file ;
var loaded = document.querySelector('script[src="'+file+'"]') ;
if (loaded) {
loaded.onload = callback ;
loaded.onreadystatechange = callback;
return
}
var script = document.createElement("script");
script.type = (typeof type ==="string" ? type : "application/javascript") ;
script.src = file;
script.async = false ;
script.defer = false ;
script.onload = callback ;
if (error) {
script.onerror = error ;
}
else {
script.onerror = function(e) {
console.error("Script File '" + _file + "' not found :-(");
};
}
script.onreadystatechange = callback;
document.body.appendChild(script);
}
You could give what ever your looking for an ID
and check whether not the ID has been loaded using document.getElementById("ID");
Is that what your looking for not sure I fully understand?

Looking for an elegant way to load JS and execute it

I'm new into JavaScript and I really like jQuery and hate when it comes to writing some cumbersome code to get simple things done.
I'm currently trying to load an external JS dynamically and execute it (to communicate with Google Translate API).
The sample code creates a script tag, sets its src and appends it to document's head to execute it:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
var sourceText = escape(document.getElementById("sourceText").innerHTML);
var source = 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + sourceText;
newScript.src = source;
// When we add this script to the head, the request is sent off.
document.getElementsByTagName('head')[0].appendChild(newScript);
I wonder if there's any one-liner in jQuery for this.
$.getScript('https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&callback=translateText&q=' + $('#sourceText').html());
Try this:
http://api.jquery.com/jQuery.getScript/
HeadJS is made for such use, this is easy and optimized way to include scripts This will helps you sure.
basic Method: ( took 800ms)
<script src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js"></script>
<script src="https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js"></script>
<script src="https://github.com/smith/scripty2/raw/master/lib/prototype.js"></script>
<script src="https://github.com/headjs/www/raw/master/content/test/jquery-ui.js"></script>
<script src="https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js"></script>
using head.js (took 700 ms)
<script src="../media/js/head.min.js"></script>
<script>
head.js("https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael.js")
.js("https://github.com/jquery/jquery-ui/raw/master/jquery-1.4.4.js")
.js("https://github.com/smith/scripty2/raw/master/lib/prototype.js")
.js("https://github.com/headjs/www/raw/master/content/test/jquery-ui.js")
.js("https://github.com/kosmas58/compass-jquery-plugin/raw/master/lib/jslint.js");
</script>
see the testcase

How do I add an external js file with a parameter

I want to give a minimal js code to random websites so that they can add a widget.
The code needs to run after the main page loads and include a parameter with the domain name. ( I don't want to hardcode it)
One option is to add this code just before the </body> (so It will run after the page loads):
<script type="text/javascript" id="widget_script">
document.getElementById('widget_script').src=location.protocol.toLowerCase()+"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
</script>
This works in IE but not in Firefox. I see with Firebug that the src property is created correctly but the script from my site is not loaded.
My question is : what is the best way to do that ? (preferably by putting minimal lines on the header part.)
To further clarify the question: If I put a script on the header part, how do I make it run after it is loaded and the main page is loaded? If I use onload event in my script I may miss it because it may load after the onload event was fired.
You can try to statically include the script with document.write (is an older technique and not recommended to use as it can cause problems with more modern libraries):
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
document.write('<script src="', url, '" type="text/javascript"><\/script>');
Or with dynamically created DOM element:
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
Later edit:
To ensure the script is run after onload this can be used:
var oldWindowOnload = window.onload;
window.onload = function() {
oldWindowOnload();
var url = location.protocol.toLowerCase() +
"//mywebsite.com/?u="+encodeURIComponent(window.location.host);
var dynamicInclude = document.createElement("script");
dynamicInclude.src = url;
dynamicInclude.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(dynamicInclude);
}
I do not believe it can be shorter than this, apart from shorter variable names :)
Why not use the getScript method of jQuery to do the loading? If you don't want to be dependant on jQuery, you can trace through the source to learn how they tackled it.
Viewing a widely used library is always going to show you solutions to problems you didn't know you had. For example, you can see how jQuery manages to generate a callback when the script is loaded, and how it avoids a purported memory leak in IE.
You probably want to be implementing the non-blocking script technique. Essentially instead of modifying the src of a script, you're going to create and append a whole new script element.
Good write up here and there are standard ways to do this in YUI and jQuery. It's quite straightforward with only one gotcha which is well understood (and documented at that link).
Oh and this:
One option is to add this code just
before the </body> (so It will run
after the page loads):
...is not technically true: you're just making your script the last thing in the loading order.

Categories

Resources