I know they do the same thing more or less, its just the approach on how its done.
<script src="example.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
function OptanonWrapper() { }
</script>
<script type="text/javascript">
var x = x || [];
(function(){
setTimeout(function(){
var d = document, f = d.getElementsByTagName('script')[0], s = d.createElement('script'); s.type = 'text/javascript';
s.async = true; s.src = "example.js"; f.parentNode.insertBefore(s,f);
}, 1);
})();
</script>
--
I am not a native js programmer so your help would be greatly appreciated.
In the first example, the second <script> tag will only execute after example.js has finished loading.
In the second example, the <script> tag that loads example.js is created dynamically and inserted into the document (in a needlessly roundabout way, if I may add my own two cents), and it will start loading asynchronously, i.e. it does not delay the execution of any <script> tags after it. The same effect could be achieved this way:
<script src="example.js" async></script>
<script>
function OptanonWrapper() { }
</script>
Read up on the <script> element on MDN for more details:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script
Related
I'm learning jQuery but I have a problem.
Here the code:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = "text/javascript";
var pt = document.createElement('script');
pt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(pt);
$(document).ready(function() {
alert("ti vedo");
$.post('wait.php', function(data) {
alert("ti vedo2");
var dati = JSON.parse(data);
alert(data);
for (var i = 0; i <= dati.length; i++) {
var node = $(document.createElement("span"));
var content = $(document.createElement("div"));
var code = dati[i];
var text = $(document.createTextNode(code));
node.append(text);
content.append(node);
$("#boxMessage").append(content);
}
});
});
I use alert to check the error, but I can't see the first alert. So the problem is $(document)... but I don't understand why. I'm making a mistake when I include the jQuery library? Thank you for the Help!
You're getting the error because you're trying to access jQuery (via $) before it's available.
You can run your jQuery-related code after the script was really loaded:
var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type="text/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
script.addEventListener('load', function(){
alert("ti vedo");
$.post('wait.php',function(data){
alert("ti vedo2");
var dati=JSON.parse(data);
alert(data);
for(var i=0; i<=dati.length; i++){
var node=$(document.createElement("span"));
var content=$(document.createElement("div"));
var code=dati[i];
var text=$(document.createTextNode(code));
node.append(text);
content.append(node);
$("#boxMessage").append(content);
}
});
});
Also, you don't need two different versions of jQuery simultaneously.
The order of activities is:
A script element to load jQuery 3.4.1 is added to the DOM
A script element to load jQuery 3.5.1 is added to the DOM
The $ function is called, but $ is undefined, so the script terminates with an exception
jQuery 3.4.1 is loaded, adding $ to the environment
jQuery 3.5.1 is loaded, overwriting $
Use a regular <script> element to load your dependencies instead of trying to load them half way through executing your script.
I have two separate script files (script1.js, script2.js). Each of the files has its own functions/variables defined in it. For the sake of simplicity, I will assume each file holds a separate variable. So the files will look like:
script1.js
var x = 2;
script2.js
var y = 2;
I am using the scripts in index.html:
index.html
<button onclick="change()">Change script</button>
<script id="file" src="script1.js"></script>
<script>
function change() {
var file = document.getElementById("file");
if(file.src.slice(-10) == "script1.js") {
file.src = "script2.js";
} else {
file.src = "script1.js";
}
}
</script>
But when I change the src attribute for the script, the loaded script does not change. So even after switching scripts, x has the value 2 while y is undefined.
How do I switch the script after the page has finished loading?
Not sure what you want to accomplish, but as far as loading of javascript is concern, you can use:
$("#id_of_button").click(function(){
$.getScript('helloworld.js', function() {
//do whatever you want to accomplish here....
});
});
More detail here
A better way may be to keep the related code in separate functions in same js file and calling the specific function to override the logic based upon your condition check. Though I'm still not clear what you are trying to achieve. Could I get some scenario based idea to get it clear?
You have to create a new script in order to loaded it, the problem is that you also want to maintain the position of the script.
So here I wrote an example that will replace the old script and insert the new one at the same position.
Read the comment to understand how this work.
function change() {
var file = document.getElementById("file"); // get the script you want to change
var newscript = document.createElement("script"); // create new script
newscript.src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" // set the new script src
newscript.setAttribute("id","file"); // set the id to the same id as the old script
newscript.type = 'text/javascript';
file.parentNode.insertBefore(newscript, file); // insert the new script before the old one
file.remove() // remove the old script
var callback= function(){ // when the script has been loded then test and see if jQuery is working now
$("body").append("<p>Jq loaded</p>"); // no error then jQuery has been loaded
}
newscript.onreadystatechange = callback;
newscript.onload = callback;
}
<script id="file" src="script1.js"></script>
<button onclick="change()">Change script</button>
You can try this: https://codepen.io/anon/pen/mvMZOR
HTML
<button type="button">Change script</button>
<script id="file" src="script1.js"></script>
Javascript
var index = 1;
var scriptId = 'file';
var button = document.querySelector('button');
button.addEventListener('click', function() {
// Remove the old script
document.getElementById(scriptId).remove();
// Create the new one
var s = document.createElement('script');
// Add the id you want, in this case "file"
s.id = scriptId;
// It will return "script1.js" or "script2.js" alternatively
s.src = 'script' + (index++ % 2 + 1) + '.js';
// Append your new script at the end of your body
document.querySelector('body').append(s);
});
Say we have the following script reference
<script src="https://pagead2.googlesyndication.com/pagead/osd.js"></script>
How to make javascript execute it several times on page load, like (in pseudo code):
<script>
var i;
for (i = 0; i < 5; i++) {
<script src="https://pagead2.googlesyndication.com/pagead/osd.js"></script>
}
</script>
You can use this piece of code to achieve what you need.
<script>
var elem = document.createElement('script');
elem.type = 'text/javascript';
elem.async = true;
elem.src = 'https://pagead2.googlesyndication.com/pagead/osd.js';
for(var i=0; i<5; i++){
var s = document.getElementsByTagName('script')[i];
s.parentNode.insertBefore(elem, s);
}
</script>
This should load as well as execute the script. #BenM
First of all I didn't understand why are you trying to add reference to same js file repeatedly. Its enough if you load the file only once. If you are trying this to execute some code inside the js file then just write that piece of code inside a function and call that function on window onload. Hope that helps
I am trying to change the src attribute of a script in the head of the page positioned below the main script. Here is a part of the code:
function loadLevel(l) {
switch (l) {
case 0:
document.getElementById("level").src = "levels/level0.js";
level0.load();
break;
case 1:
document.getElementById("level").src = "levels/level1.js";
level1.load();
break;
}
level = l;
}
And the code of the script:
<script id="level" src=""></script>
When the function loadLevel(l) is called the switch checks the value of l, changes the value of the source of the script called "level" accordingly and calls the right loading function. The objects level0 and level1 and their load functions are stored respectively in the files level0.js and level1.js.
But when I do this, it won't work. level0.js and level1.js have no mistakes in them because when I do this it does load level 0, but obviously not level 1 when I press the button to do so:
<script id="level" src="levels/level0.js"></script>
When you load a new script the process is async, so calling the function stright after wont work as the script wont have loaded, you'd need a call back once complete.
function loadLevel(level) {
(function(d, script) {
script = d.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.onload = function(){
/*
Your script has loaded
You can now call the code you have loaded
*/
};
script.src = '/levels/level' + level + '.js';
d.getElementsByTagName('head')[0].appendChild(script);
}(document));
}
I refer you to use modules instead of using regular scripts.
Here is the code you can use:
async function loadLevel(l){
let {load}= await import("/levels/level"+l+".js");
load();
}
And in your level scripts:
function load(){
//Your code
}
export {load};
And some references for modules:https://javascript.info/modules-intro, https://javascript.info/import-export, https://javascript.info/modules-dynamic-imports
And here is my example code on Github: https://github.com/Learndev-student/Example/tree/main/Example%20001
And see it running on web: https://learndev-student.github.io/Example/Example%20001/index.html
Ok, here goes my first question on here.
Setup: We use a javascript based tool to A/B test our landing page designs. I need version A (control) to link to one external javascript file, and version B (variation) to link to an alternate javascript file.
Goal: to have an internal js script at the bottom of the control that looks to see if the tool is in fact serving A or B, and if true, which one was served. The result indicates which external script should be linked.
Issue: regardless of if the tool is in fact serving A or B, the original script is linked first, then if the tool is detected, the appropriate script is linked after that.
Here is my code (I apologize in advance for any newbie mistakes):
//script at bottom of original or tool-served control html page template
<script type="text/javascript">
valForTool = function () {
var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
if (variationId == 1) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts.js';
document.body.appendChild(newScript);
};
}
originalValidation = function () {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts.js';
document.body.appendChild(newScript);
}
$(function(){
if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
valForTool();
} else {
originalValidation();
};
});
</script>
//end script on control or original template
//script on tool-served variation html template - will run after the above script
<script type="text/javascript">
$(function() {
$('#project_info input[type=submit]').removeAttr('disabled');
$('#project_info').unbind();
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts2.js';
document.body.appendChild(newScript);
$('.input_text').parent().addClass('contact_field');
});
</script>
// end script on variation template
Any ideas as to what I'm doing wrong? Did I provide enough information? Thanks! I love this site as a reference for my questions, but this is my first time actually posting one.
Shortening it down a bit, it seems like your just doing this:
<script type="text/javascript">
$(function(){
if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
if (variationId == 1) {
$.getScript('js/scripts.js', function() {runSecond();});
}
}else{
$.getScript('js/scripts.js', function() {runSecond();});
}
function runSecond() {
$('#project_info input[type=submit]').removeAttr('disabled').unbind();
$.getScript('js/scripts2.js');
$('.input_text').parent().addClass('contact_field');
}
});
</script>
Now looking at that, it's obvious that both scripts are running no matter what conditions are met in those if/else statements, and I don't really get what it is your trying to do, but the first thing i would do, is to add some console.logs to see if those if/else statements are working like they are supposed to, and then figure what scripts should be loaded under which conditions etc ?