Adding external js script dynamically to iFrame and execute function from it - javascript

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 ?

Related

$/jQuery not defined when dynamically adding scripts

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";

How to inject Jquery into safari extension builder?

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.

Difference between calling a script in the onload event or placing code at end of html

I was reading the google maps api documentation and stumbled across a paragraph that explains the Asynchronously Loading the API. The api documentation can be found here
As an example it showed a script that looks like this:
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
What is the difference between this piece of code and just simply adding the script call all the way to the end of the html markup? Like this:
<!-- rest of the markup -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize"></script>
</body>
</html>
You usually want your JS scripts to run after the DOM is loaded and this event doesn't necessarily occur when your html is read/parsed. I.E. There exists some time between reading the HTML and building the DOM that your JS needs to traverse.

javascript dynamically creating script block

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);
});

How can I tell a dynamically inserted <script> tag to… run

I'm dynamically inserting a <script> tag with a src attribute and no content. But the browser does not pull down that src and run the script after the insertion -- the tag just sits there in the DOM.
Is it possible for me to tell the browser to "run" the script tag?
Because of the other code I'm working with, it's easier for me to keep the code fetched via the src attribute than to fetch it myself and insert it into the body of the tag -- but if that's necessary, I can do that too (and welcome any advice on that).
update with requested info
The script tag is inserted based on user interaction an arbitrary number of times after the page has loaded
I'm inserted the tag like this (jquery's html function strips out script tags): document.getElementById("my-div").innerHTML = "the script tag, which stack overflow wants to strip";
Try following code:: Its working
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src =MY_URL;
$("#YOUR_ELEMNT_ID").append( script );
it should run right after the browser inserts the script into the dom, but you can try to wrap your script into a function and call that function after the script loads :
var script = document.createElement('script');
script.setAttribute('type','text/javascript');
script.setAttribute('src',script_url);
script.onreadystatechange= function () {
if (this.readyState == 'complete')
initScript();//the whole script is wrapped in this function
}
script.onload= initScript;
Hope this helps!
You could have a setTimeout in the main script to check if the new script is there.. and if it is, then run it. Do you know if it downloads the file or if it just does nothing? Check with Chrome's Network monitor.
I think there's a dynamic way to load Javascript without the src= tag, as well, but I haven't personally done it.
Why not have all the javascript pre-loaded and just put through some inline JS to execute it?

Categories