Dynamically Add js file at the end of the page using javascript? - javascript

I want to add one js file at the bottom of the page before </body> tag.
I am trying one format. But its not working properly.
My code
var url = 'sample.js';
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName('body')[0].appendChild(script);
But its not working.
Now i check
var x = document.getElementsByTagName('body');
alert(x.length);
its shows 0
How can i add this js file into my bottom of the page. Please advise

See this code
var body = document.body;
alert("Body when page loading: " + body);
document.addEventListener("DOMContentLoaded", function() {
var bodyLoaded = document.body;
alert("Body when page loaded: " + bodyLoaded);
var url = "http://code.jquery.com/jquery-1.10.2.min.js";
var script = document.createElement('script');
script.type = "text/javascript";
script.src = url;
script.onload = function(){
var testP = $("<p></p>");
testP.html("JQuery worked");
$(document.body).append(testP);
}
bodyLoaded.appendChild(script);
});
If first alert you get null. But in second (when body loaded) you get HTMLBodyElement. This is your mistake if you try to append element to body in head before body loaded.

You are writing your this code in the head section and at the time this executes body element is not yet created. This is the only reason for error. Keep this code after body element is created.

Related

Reloading a dynamically loaded script

I am loading the mathJax javascript library over their CDN dynamically their CDN dynamically. This is so I can apply it to a html partial page I am loading at the same time.
As it stands, the scripts will load once but not reload when the html partial page changes. I have tried using a timestamp on the CDN URL and removing the scripts from the DOM, among other things. I have been trying to solve this all afternoon with no success. There are no errors appearing.
So, is there anything else I can try to get the scripts to reload with each new html snippet? Thanks a ton for any suggestions. Here is my code:
$scope.getLesson = function (x)
{
$scope.lessonMenu = false;
$scope.hiddenMenuLink = true;
x = x.replace(/[\s]/g, '');
$scope.parse = $parse(x)($scope);
var i = 0;
$.get("Lessons/" + x + ".html", function (data) {
// send the current html to view
$scope.currentLessonHTML = data.toString();
// destroy mathjax if existing
if (i > 1 && script1.parentNode != null) {
script1.parentNode.removeChild(script1);
script2.parentNode.removeChild(script2);
i = 0;
}
// loading the MathJax dynamically
var head = document.getElementsByTagName("head")[0];
var script1 = document.createElement("script");
var script2 = document.createElement("script");
var responsibleSibling = document.createElement("script");
var mathJax = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" + "?nocache=" + new Date().getTime();
var mathJaxConfig = 'MathJax.Hub.Config({extensions: ["tex2jax.js"], jax: ["input/TeX", "output/HTML-CSS"],tex2jax: {inlineMath: [ ["$","$"], ["\\\\(","\\\\)"] ],displayMath: [ ["$$","$$"], ["\\[","\\]"] ],processEscapes: true},"HTML-CSS": { availableFonts: ["TeX"] }});';
script1.type = "text/x-mathjax-config";
script1[(window.opera ? "innerHTML" : "text")] = mathJaxConfig;
head.appendChild(script1);
script2.type = "text/javascript";
script2.src = mathJax;
head.appendChild(script2);
i++;
// apply new lesson
$scope.showLesson = true;
$scope.$apply();
});
}
I finally figured this out. The script was being reloaded, but it was not applying the typeset specific to the Mathjax library. The solution is a built-in function to queue the typeset to async operations, like such:
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
http://docs.mathjax.org/en/latest/typeset.html
Thanks for feedback.

Loading Inline Javascript through an AJAX load through jQuery

I have a similar problem to this question.
Loading Javascript through an AJAX load through jQuery?
I want to load an HTML page into a div container using Ajax and JQuery's .load() . The html page has javascript on it that loads a weather widget from http://www.showmyweather.com/
This is the script:
<script type="text/javascript" src="http://www.showmyweather.com/weather_widget.php? int=0&type=js&country=ca&state=Ontario&city=Hamilton&smallicon=1&current=1&forecast=1&background_color=ffffff&color=000000&width=175&padding=10&border_width=1&border_color=000000&font_size=11&font_family=Verdana&showicons=1&measure=C&d=2013-11-11"></script>
I don't know how to include the widget in the DOM other than placing the script inline the html page. If there is a way to use this script and add it in using $.getscript(); that would be nice, but I can't figure it out.
var element = document.createElement("iframe");
document.body.appendChild(element);
var frame = window.frames[windows.frames.length - 1];
frame.document.write('<scr' + 'ipt type="text/javascript" src="http://www.showmyweather.com/weather_widget.php?int=0&type=js&country=ca&state=Ontario&city=Hamilton&smallicon=1&current=1&forecast=1&background_color=ffffff&color=000000&width=175&padding=10&border_width=1&border_color=000000&font_size=11&font_family=Verdana&showicons=1&measure=C&d=2013-11-11"></sc'+ 'ript>');
This is the way it's done with mootools in Asset.javascript:
var loadScript = function (source, properties) {
properties || (properties = {});
var script = document.createElement('script');
script.async = true;
script.src = source;
script.type = 'text/javascript';
var doc = properties.document || document, load = properties.onload || properties.onLoad;
return delete properties.onload, delete properties.onLoad, delete properties.document,
load && (script.addEventListener ? script.addEventListener("load", load) : script.attachEvent("readystatechange", function() {
[ "loaded", "complete" ].indexOf(this.readyState) >= 0 && load.call(this);
}))
doc.getElementsByClassName("head")[0].appendChild(script);
}
Now you can call loadScript("script url", {document: window.frames[0].document}) and it will load the script in the window. Just need to pass it an external document in options and a script.

How to dynamically remove script from a page

What i am trying is -
http://jsfiddle.net/jhrz9/1/
to remove the script generated when someone clicks the button #goBack button
Now i am able to create and append script and style tags when the user clicks the #runMyCode
But as soon as i go back to the previous screen using #goBack button the script stays on the screen, now what i want to do is to remove that script and create another one again when i click the #runMyCode button
Now i am trying this -
var newScript = document.createElement('script'); ;
var newTextNode=document.createTextNode($("#jsTextArea").val());
newScript.type = 'text/javascript';
newScript.appendChild(newTextNode);
document.body.appendChild(newScript);
$('#goBack').click(function(){
newTextNode.parentNode.removeChild(newTextNode);
});
But for some reason it is not working....
you have to give the script an id.
$("#runMyCode").click(function(){
$("#resultContainer").html($("#htmlTextArea").val());
var newScript = document.createElement('script');
newScript.id = "goback_script";
var newTextNode=document.createTextNode($("#jsTextArea").val());
newScript.type = 'text/javascript';
newScript.appendChild(newTextNode);
document.body.appendChild(newScript);
var newStyle = document.createElement('style');
var newTextNode2=document.createTextNode($("#cssTextArea").val());
newStyle.type = 'text/css';
newStyle.appendChild(newTextNode2);
document.body.appendChild(newStyle);
});
$('#goBack').click(function(){
var script = document.getElementById("goback_script");
script.parentElement.removeChild(script);
});
jsFiddle

How to include javascript file in a specific tag?

Ok, I've got this function:
/* jsHandler.js */
function inc(filename)
{
var body = document.getElementsByTagName('body').item(0);
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
body.appendChild(script)
}
What i would like is extending the script to tell js where to insert the js.file, like, say i have this in html:
<div id="mydiv"></div>
<iframe id="myiframe"></iframe>
i call
inc(this.js, mydiv)
to include the js.file in the div "mydiv",
resulting in:
<div id="mydiv"><script src="this.js" type="text/javascript"></script></div>
How do i do that?
Try this...
/* jsHandler.js */
function inc(filename,target)
{
var targetelement= document.getElementById(target); // get the target element
script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
targetelement.appendChild(script); // add the script to the target
}
You always pick your body element
var body = document.getElementsByTagName('body').item(0);
and simply append the script tag to it:
body.appendChild(script)
What you want to do
Pick your target element and append it there.
var target = document.getElementsById(mydiv);
// ... other code lines
target.appendChild(script)

Insert a Script into a iFrame's Header, without clearing out the body of the iFrame

I'm looking to add a script to an iFrame's header while not losing everything contained in the iFrame's body or header...
here is what I have right now which does update the iFrame with the new script, but it cleans everything in the iframe out, not appends which is what I'd like. thxs! B
// Find the iFrame
var iframe = document.getElementById('hi-world');
// create a string to use as a new document object
var val = '<scr' + 'ipt type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></scr' + 'ipt>';
// get a handle on the <iframe>d document (in a cross-browser way)
var doc = iframe.contentWindow || iframe.contentDocument;
if (doc.document) { doc = doc.document;}
// open, write content to, and close the document
doc.open();
doc.write(val);
doc.close();
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'yourpath';
headID.appendChild(newScript);

Categories