How to append <script> to Head or Body Using Javascript? - javascript

I have a JavaScript problem.
I searched on google how to append using javascript and I found an example. I want to manually append a script tag to head or body, but the example just appends in the head.
I edited the example so that the script tag can be appended in the head or body, but the code doesn't work.
Can anyone help me fix my problem? And please show me the demo on jsfiddle :D
Thanks :)
Here my script:
//JS
//Defined with loadjscssfile("yourcssurl.js", "js", "head"); or addCss("yourcssurl.js", "js", "body");
//CSS
//Defined with loadjscssfile("yourcssurl.css", "css", "head"); or addCss("yourcssurl.css", "css", "body");
function loadjscssfile(filename, filetype, pos) {
if (filetype == "js") { //if filename is a external JavaScript file
var fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref == filetype) {
document.getElementsByTagName(pos)[0].appendChild(fileref)
}
else if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile("myscript.js", "js", "body") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js", "body") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css", "body") ////dynamically load and add this .css file
And here is the original script, before I edited: Dynamically loading an external JavaScript or CSS file
Sorry for my bad english :)

You can learn from google to appending scripts dynamically
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
I'm not sure what you are trying to achieve at the end of the day, but take a good look at the script, it's async. So you do not worry about the sequence of the resource loading.
In some use cases, you might need to control the sequence of the script loading, you can consider using RequireJS or Modernizr

You are pretty close, but you don't need the extra if condition you added, this should be sufficient:
function loadjscssfile(filename, filetype, pos) {
var fileref;
if (filetype === "js") { //if filename is a external JavaScript file
fileref = document.createElement("script");
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", filename);
}
else if (filetype === "css") { //if filename is an external CSS file
fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
}
if (fileref) {
document.getElementsByTagName(pos)[0].appendChild(fileref);
}
}
Give that a shot.

Related

Download file generated by javascript in android webview

I have an android app with a webview.
Whenever a user clicks on a button, JavaScript creates a blob, puts text in it and downloads it.
Here's the function that does this:
function saveTextAsFile(A)
{
FillTextToWrite(A);
var textFileAsBlob = new Blob([textToWrite], {
type: 'text/plain'
});
var downloadLink = document.createElement("a");
downloadLink.download = "Analysis.txt";
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
It works fine in any browser, but when I try to download it in the app, nothing happens.
Is there a way to download the blob in the app or is it easier to change the JavaScript?
I need the JavaScript to work on browser as well as on the android app, so sending the blob to the android app in JavaScript will not work on browser.
The solution I found was to detect wheter the javascript is running in Android app or in browser (by adding a string to the user agent).
When in Android app I am sending variable textToWrite (which would normally go into the blob) to the java.
In javascript:
if(App){
Android.sendData(textToWrite);
} else {//make blob}
In java:
myWebView.addJavascriptInterface(new myJavascriptInterface(this), "Android");
public class myJavascriptInterface {
Context mContext;
myJavascriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void sendData(String data) {
//save data as file
}
}

Embed SWF in JavaScript

i want to embed swf into javascript, i know there is a method to do this, but how do i do it? here is my javascript
<script type="text/javascript">
adroll_adv_id = "JD5ZGBNO4RBYVAMMMPX3J7";
adroll_pix_id = "CEJOJM5N5VAHBKCVMT2DML";
(function () {
var oldonload = window.onload;
window.onload = function(){
__adroll_loaded=true;
var scr = document.createElement("script");
var host = (("https:" == document.location.protocol) ? "https://s.adroll.com" : "http://a.adroll.com");
scr.setAttribute('async', 'true');
scr.type = "text/javascript";
scr.src = host + "/j/roundtrip.js";
((document.getElementsByTagName('head') || [null])[0] ||
document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
if(oldonload){oldonload()}};
}());
</script>
I have a flash banner actually, and i want to call this javascript into that banner
If you want to call javascript function from flash, then you need to call like this from your flash code,
Externalnterface.call("function_name","arg");
You need to import the library flash.external.ExternalInterface;

Loading Javascript and checking once it has loaded

I am using the following JavaScript code and I am trying to find out once the file has been downloaded and added to the header of my page:
function loadjscssfile(filename, filetype)
{
if (filetype=="js"){ //if filename is a external JavaScript file
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", filename)
}
else if (filetype=="css"){ //if filename is an external CSS file
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
loadjscssfile("jquery.js","js");
I normally use the following code to find out once my image has loaded:
document.getElementById("header_logo").src = "logo.png"; // load top logo
var header_logo = document.getElementById("header_logo");
header_logo.onload = function(e) {
// do something here, the file has loaded
}
but I can't work out how to check once my JS has been loaded..
Any ideas?
(I can't use jQuery.)
You could add a function to the onload event:
function loadjscssfile(filename, filetype, onload) {
//if filename is a external JavaScript file
if (filetype == "js") {
var fileref = document.createElement('script');
fileref.type = "text/javascript");
fileref.onload = onload;
fileref.src = filename);
document.getElementsByTagName("head")[0].appendChild(fileref);
return;
}
//if filename is an external CSS file
if (filetype == "css") {
var fileref = document.createElement("link");
fileref.rel = "stylesheet";
fileref.type = "text/css";
fileref.onload = onload;
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref);
return;
}
}
loadjscssfile("jquery.js","js", function() { alert(this.src); });
In HTML 4.01 the load event was onlly supported by body and frameset elements, though many support it for img elements and some for script elements.
In HTML5, script elements have beforescriptexecute, afterscriptexecute and load events that are dispatched at relevant times in the script element's life. However, support for those events is likely not available in many browsers in use so not to be relied upon.
The most robust way to see if a script has loaded is to test for a value of a variable that is assigned a value by the last bit of code to be executed, e.g. final statements like:
var loadedScripts = loadedScripts || {};
loadedScripts.fooScript = true;
Then you can test for it:
if (loadedScripts.fooScript) {
// loaded
} else {
// not loaded
}

Read/write text file from javascript in objective-c project

I am making an app for iPhone and in that I am using Javascript for making making embeded youtube in UIWebView. I want to open/read/write a file on some events from javascript and then want to use that file in objective-c code. But how can I do this? I mean at what location can I save and open the file.
I have made a file called youtubeAPI.html and calling this file from objective-c code. It opens the page successfully. Now I want to open a file and write the something everytime it changes it states, and then need to to show that file in the final result from obejective-c. Please tell me how can i do this.
<!DOCTYPE HTML>
<html>
<body>
<div id="player"></div>
<script>
//Load player api asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) { // NEED TO ADD FILE OPERATION HERE
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
THanks
Akansha
// Get file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString filePath = [documentsDirectory stringByAppendingPathComponent:filename];
// Read file contents
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
// Write file contents
[[content dataUsingEncoding:NSUTF8StringEncoding] writeToFile:filePath atomically:NO];
UIWebView is a sandbox, there is no chance to do this, javascript can not access file system directly, this is what i know.
But you can do other thing.
first: save state into window object;
such as window.state = "someting";
second: read the state by Objective-C;
NSString *state = [webView stringByEvaluatingJavaScriptFromString:#"window.state"];

cache wav file using javascript

When I load a sound file with Javascript, the file seems to load from remote server each time. Is it possible to cache the file once loaded? I would like to load once and play as required.
var soundEmbed = null;
function playSound()
{
var myWAVfile = "myfile.wav";
if (soundEmbed)
{
document.body.removeChild(soundEmbed);
}
soundEmbed = document.createElement("embed");
soundEmbed.setAttribute("src", myWAVfile);
soundEmbed.setAttribute("hidden", true);
soundEmbed.setAttribute("autostart", true);
document.body.appendChild(soundEmbed);
}

Categories