I am dynamically adding <script> tags for different .js resources into the head, however I receive an error exclaiming that jQuery is not defined.
I know that jQuery is in fact working, as other functions further down the flow are working correctly. Below is the code that I am using to dynamically add these scripts to the header. As you can see, I also include jQuery before any other plugins.
document.addEventListener("DOMContentLoaded", AddExternals)
function AddExternals(){
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
var t2e = document.createElement("script");
t2e.type = "text/javascript";
t2e.src = "/test/rfsystem/rfJavascript/table2excel.js";
document.getElementsByTagName("head")[0].appendChild(jq);
document.getElementsByTagName("head")[0].appendChild(t2e);
console.log(jQuery);
}
Just after appending the script tag you can not expect that the script has been pulled over from the network and is embedded on to your page. It will load asynchronously.
You need to wait, or you can use .onload on that script.
Ex:
You should also append the script to the DOM before attaching the onload event and You should set the src attribute after the onload event:
var jq = document.createElement("script");
jq.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(jq);
jq.onload = function() { console.log(jQuery); };
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js";
Related
I'm creating an iFrame dynamically and I've injected an external js library to it.
Everything is working fine. I have my iFrame builded containing the script tag with the library in the head tag of the library. Now I would like to execute a function that is written in that library. Here is the code that I use to add the script dynamically:
var head = parentFrameContentWindow.getElementsByTagName('head')[0];
var script = parentFrameContentWindow.createElement('script');
script.src = "http://localhost:8080/project/js/project-interactions.js";
script.type = 'text/javascript';
script.onload = function() {
}
head.appendChild(script)
I've added the onload attribut to the script tag but when I try to fire up a simple function that triggers an alert method contained but the external library, I get and undefined function error. Someone knows how to achieve that ?
A client is using Sharetribe which allows you add custom JS via admin, but only in the head. I want my script to load after jQuery, but jQuery is loaded at the end of the body. How can I write vanilla JS that adds my main script to the end once the doc loads?
I tried this:
<script>
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://cdn...";
document.body.appendChild(script);
var script2 = document.createElement("script");
script2.type = "text/javascript";
script2.text = "$(SOME.CODE.HERE);"
document.body.appendChild(script2);
</script>
But it gets executed before the document is finished loading (and in particular, before jQuery is available). The only thing I can think of is to set a timer, but that seems buggy.
Any advice?
Use DOMContentLoaded event:
The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).
document.addEventListener("DOMContentLoaded", function (event) {
console.log("DOM fully loaded and parsed");
// Your code here
});
DOMContentLoaded is same as ready event of jQuery.
Documentation
Tell your code to wait for the DOM to finish loading:
window.onload = function() {
var script = document.createElement("script");
script.type = "text/javascript";
//....
}
Or using jQuery:
$(document).ready(function() {
var script = document.createElement("script");
script.type = "text/javascript";
//....
});
As you're waiting for jQuery to load, you can simply wrap your code within jQuery's $(document).ready() method:
$(document).ready(function() {
// Your code here.
});
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
I realise that you've mentioned that you want this in "vanilla" JS, but as you're waiting for jQuery to load anyway this seems a bit redundant.
When the browser run your code in <head>, the <body> element didn't existed yet. So, document.body was null.
To create a script a the <body> element, use 'load' event of document, for example:
.............
document.addEventListener('load', function(event){
var script = document.createElement('script');
...............
document.body.appendChild(script);
}, false);
............
$(document).ready(){} is executed when your dom element render successfully.
I have done the global page file as
<script>
safari.application.addEventListener("command", performCommand, false);
function performCommand(event) {
if (event.command == "open-nettuts") {
$('div.spaceball').hide();
}
}
</script>
And in the start scripts I have put a jquery.js file. Why when I click on the toolbar button does it not hide the div with the class="space ball" on this page?
You can't access to web content, but you can inject js to page, wich modify something. See Safari Extensions Development Guide page 16.
To work on web content write in inject.js
var script = document.createElement("script");
script.type = "text/javascript";
//script.src = "path/to/your/javascript.js"; // use this for linked script
script.text = "alert('voila!');" // use this for inline script
document.body.appendChild(script);
See Can't append element.
I have a pixel script I want to insert only on a certain page. Because of our awful CMS, I can't add it to the page itself, but I can add it to the master template ASP (I think it's ASP) file. I figured it would be easiest to do this in Javascript.
Right now I have this in the head, but I don't think printing the pixel script in the head will work:
<script>
if (location.href.indexOf("http://site.com/page1") !== -1) {
document.write('<script src="yadayada" type="text/javascript"></script>');
}
</script>
<script>
if (location.href.indexOf("http://site.com/page1") !== -1) {
var script = document.createElement("script");
script.src="yadayada.js";
script.type="text/javascript";
script.onload=function(){
// callback after script loading is complete
// your script dependent code goes here
}
document.body.appendChild(script)
}
</script>
This is how it can be done
Obviously, it would be better to do this on backend, but if you really can not, here is what is wrong with your code:
The </script> part of the string you are trying to append to the document is actually closing your script tag in the head.
This is a common approach to avoid this problem:
document.write('<script src="yadayada" type="text/javascript"></' + 'script>');
Other solution would be to create the script element using document.createElement:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "example.com/somescript.js";
document.body.appendChild(script);
I have a question about inserting a dynamically created script with JavaScript.
This is the code I'm using:
var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'code.js';
body.appendChild(script);
I usually place scripts at the bottom of the page, but if it's dynamically inserted like this, is there a way to ensure that the script is placed at the bottom of the page?
If it's dynamically inserted like this, is there a way to ensure that the script is placed at the bottom of the page?
You already do that with body.appendChild(script); of course there might be other elements inserted after it later on.
However, as you are dynamically inserting the script, there is absolutely no need to ensure placing it at any certain location - it is loaded and executed asynchronously (neither blocking something nor waiting for something). You may place it anywhere in the document, and even remove it right away, it will not influence any load or execute behaviour.
There's a way to ensure that using Jquery. The code.js will be called after DOM is loaded and putted right before </body> tag:
$(function() {
var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'code.js';
body.appendChild(script);
});