How to add javascript file dynamically in the head of html? - javascript

From below code I am trying to load javascript file TestJScript.js dynamically and after loading want to call javascript function LoadData() exist in that file. But I am getting error please check image.
Note: Error get only on IE-8.0.6001 update 0.
Please suggest me correction such that It will work from 6 to all version of IE.
Or any another solution.
if it require any windows updates. Please let me know.
Please don't suggest with JQUERY code
Javascript file code :
function LoadData() {
alert('ok');
}
Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function LoadJSFile() {
var js = document.createElement("script")
js.setAttribute("type", "text/javascript")
js.setAttribute("src", "C:\\TestJScript.js")
document.getElementsByTagName("head")[0].appendChild(js)
//call below function exist in TestJScript.js file
LoadData();
}
</script>
</head>
<body onload="LoadJSFile();">
</body>
</html>
Error Image:

Try this http://dustindiaz.com/scriptjs.
Like this:
$script('yui-base.js', function() {
// do stuff with base...
$script(['yui-anim.js', 'yui-connect.js'], function() {
// do stuff with anim and connect...
});
$script('yui-drag.js', function() {
// do stuff with drag...
});
});

The error reports a problem in the javascript file that you're loading. So the problem lies not in how you dynamically load the javascript file, but in the javascript file itself.

It looks like there is a problem with the file once it has loaded. Are you sure there is no syntax error in the file itself.
Also, I would recommend you use a relative path to the javascript file instead of the absolute path.
EDIT:
Try this:
function LoadJSFile() {
var script = document.createElement('script');
script.src = "C:\\TestJScript.js";
script.onload = function () {
LoadData();
};
document.getElementsByTagName("head")[0].appendChild(script)
}

You could try the following:
<script>
function LoadJSFile(src, callback) {
var js = document.createElement('script');
js.src = src;
js.async = true;
js.onreadystatechange = js.onload = function() {
var state = js.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
document.getElementsByTagName('head')[0].appendChild(js);
}
LoadJSFile('C:\\TestJScript.js', function() {
LoadData();
});
</script>

If you are using c# code then another solution to solve this script error is, invoke script through c# code.
Code:
/
/Assiging html value to control
webBrowser.DocumentText = "HTML content";
//Calling document load completed event
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlDocument htmlDocument = webBrowser.Document;
HtmlElement htmlElementHead = htmlDocument.GetElementsByTagName("head")[0];
HtmlElement HtmlElementScript = htmlDocument.CreateElement("script");
HtmlElementScript.SetAttribute("text", "C:\\TestJScript.js");
htmlElementHead.AppendChild(HtmlElementScript);
htmlDocument.InvokeScript("LoadData");
webBrowser.DocumentCompleted -= webBrowser_DocumentCompleted;
}

Related

JS script execution at content loaded via AJAX

I have some simple code like this:
JS:
function load (element, url) {
element.innerHTML = '';
fetch(url).then(function (resp) {
return resp.text();
}).then(function (content) {
element.insertAdjacentHTML('afterbegin', content);
});
}
Content of url parameter of load function:
<div>
<button id="some-button">Execute click!</button>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});
});
</script>
My question is: Why click event (or any other JS code) does not work? HTML content is loaded, script tag also do, but JS code does not executing. I just want to replace jQuery function load with custom function load described above.
Thanks in advance!
I think JS code included like that does not get recognized as JS code. I mean, text containing <script> tag is not considered as JS code and not run. Tried the following and it seems to work. Not sure if this solves your requirement, but it might help you understand the issue. Note the usage of document.createElement('script')
<div id="content"></div>
<script>
var scr = `document.getElementById('some-button').addEventListener('click', function () {
alert('Click at button has been executed.');
});`;
var content = `<div><button id="some-button">Execute click!</button></div>`;
document.getElementById('content').insertAdjacentHTML('afterbegin', content);
var sel = document.createElement('script');
sel.text = scr;
document.getElementById('content').appendChild(sel);
</script>
Here is final working code:
fetch(url).then(function (resp) {
return resp.text();
}).then(function (body) {
element.insertAdjacentHTML('afterbegin', body);
let scripts = element.getElementsByTagName('script');
for (let scr of scripts) {
var scriptContent = scr.innerText;
var newScript = document.createElement('script');
newScript.text = scriptContent;
scr.remove();
element.appendChild(newScript);
}
});

Loading external JavaScript file

I have a cross platform app built using PhoneGap/Cordova.
I am trying to implement a function that runs an external JavaScript file when a controller loads. I am following a solution from HERE. And similarly HERE. But I want the JavaScript to execute without the window.open event, i.e. I want to run executeScript as soon as the device is ready.
How do I call the executeScript() without defining the var ref first though?
var navigation = angular.module("navigation", []);
navigation.controller("Navigation", function ($scope) {
var init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
};
init();
function onDeviceReady() {
// LOAD EXTERNAL SCRIPT
var ref = window.open('http://www.haruair.com/', '_blank', 'location=yes, toolbar=yes, EnableViewPortScale=yes');
ref.addEventListener("loadstop", function () {
ref.executeScript(
{ file: 'http://haruair.com/externaljavascriptfile.js' },
function () {
ref.executeScript(
{ code: 'getSomething()' },
function (values) {
var data = values[0];
alert("Name: " + data.name + "\nAge: " + data.age);
});
}
);
});
});
You could try to add the script in the index.html file and do whatever you want from JS. Also, you must add to your whitelist this endpoint.
<!-- index.html -->
<script>
function onCustomLoad() {
//do stuff
}
</script>
<script src="your-custom-script" onload="onCustomLoad"></script>
you could use
var script = document.createElement("script");
script.type = "text/javascript";
script.id = "some_id";
script.src = 'http://haruair.com/externaljavascriptfile.js';
document.head.appendChild(script);
then call the function once finished

How to import the external JS with callback function?

I am using Google API, based on their link I have to put the following script in the HTML file
<script src="https://apis.google.com/js/client.js?onload=callback"></script>
The custom callback function is being loaded after the client.js is loaded successfully.
function callback() {
var ROOT = 'https://your_app_id.appspot.com/_ah/api';
gapi.client.load('your_api_name', 'v1', function() {
doSomethingAfterLoading();
}, ROOT);
}
I would like to
Separate HTML with JS file
I downloaded the client.js file and put it in my local repo. But for reducing web request I would like to concat the client.js with other JS file. But I have no idea how to load the content with the concatenated JS file with the callback is being called
Thanks in advance
If you are looking for javascript only solution:
var sScriptSrc = "https://apis.google.com/js/client.js?onload=callback"
loadScript(sScriptSrc);
function loadScript(sScriptSrc) {
var oHead = document.getElementsByTagName("HEAD")[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
oHead.appendChild(oScript);
oScript.onload = loadedCallback();
}
function loadedCallback() {
alert("WoHooo I am loaded");
}
See it running here: JSFiddle
EDIT
Let me do some refining, if I understand correctly what you want to achieve:
I made a simple main html page:
<html>
<head>
<script src="client.js"></script>
</head>
<body>
PAGE BODY
</body>
</html>
Which is loading client.js
client.js contains:
// you can call this function with
// param1: src of the script to load
// param2: function name to be executed once the load is finished
function loadScript(sScriptSrc, loadedCallback) {
var oHead = document.getElementsByTagName("HEAD")[0];
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.src = sScriptSrc;
oHead.appendChild(oScript);
oScript.onload = loadedCallback;
}
// let's load the Google API js and run function GoggleApiLoaded once it is done.
loadScript("https://apis.google.com/js/client.js", GoggleApiLoaded);
function GoggleApiLoaded() {
alert("WoHooo Google API js loaded");
}
Of course, instead of GoggleApiLoaded example function you could run a method which start the loading of different js and the callback of that one could load a next one and so on...
Is this what you were looking for?
jQuery has a nice method for this. https://api.jquery.com/jquery.getscript/
jQuery.getScript("https://apis.google.com/js/client.js", function() {
console.log("hello");
})
If you want to be compatible with IE, including IE 9, you can use this async JS file loader & callback:
function loadAsync(src, callback){
var script = document.createElement('script');
script.src = src;
script.type = 'text/javascript';
script.async = true;
if(callback != null){
if (script.readyState) { // IE, incl. IE9
script.onreadystatechange = function() {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = function() { // Other browsers
callback();
};
}
}
a=document.getElementsByTagName('script')[0];
a.parentNode.insertBefore(script,a);
}
loadAsync("https://www.example.com/script.js", callbackFunction);
function callbackFunction() {
console.log('Callback function run');
}

How to call script jquery when web page is showned?

my process is when user click button print in first form then process is redirect to second page. Now when second page is showed i want to call jquery .How can i do , Please help. because i want to get html from second page.
this is my code in web
<script>
$(function () {
setTimeout(function () { printForm() }, 3500);
function printForm() {
window.onload(function () {
<%testMethod();%>
});
}
});
</script>
this is my code in code behide
public void testMethod() {
if (!Page.IsPostBack)
{
WebClient MyWebClient = new WebClient();
string html = MyWebClient.DownloadString(Session["url"].ToString());
}
}
But the problem is testMethod is calling before scond page is show. i want to do like window.print()
If I understand you correctly, you want to get jquery when other page loads, to do that with js only, you have to do something like this:
your_server ="some_server_name"
(function() {
var jquery_scrpt = document.createElement('script'); jquery_scrpt.type = 'text/javascript'; jquery_scrpt.async = true;
jquery_scrpt.src = 'https://' + your_server + '//code.jquery.com/jquery-1.11.2.min.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(jquery_scrpt);
})();
this will add jquery dynamically to your page.Hope that helps.

How to use an external javascript file in asp.net

I wrote a script to hide and show a loader for my asp.net web application. The script works great when placed inline. I tried to extract the script to an external file and received the following error:
Error: The value of the property 'Pausing' is null or undefined, not a Function object
I tried to look up the error, but I was unable to find a solution to the problem. I am new to asp.net so it may be that I'm not sure how to search for the right question.
My inline code that works is:
<script type="text/javascript">
function Pausing() {
window.setTimeout(ShowLoader, 1);
}
function ShowLoader() {
if ((typeof Page_IsValid === 'undefined') ||
(Page_IsValid != null && Page_IsValid)) {
var i = document.getElementById("loader");
var img = document.getElementById("img");
i.style.display = "block";
setTimeout("document.images['img'].src=document.images['img'].src", 10);
Endpausing();
}
}
function HideLoader() {
var i = document.getElementById("loader");
i.style.display = "none";
}
function Endpausing() {
window.setTimeout(HideLoader, 4000);
}
</script>
The event call is attached to an asp:button control below:
<asp:Button ID="btnGetReport" runat="server" OnClick="btnGetReport_Click" OnClientClick="Pausing();" />
I removed the inline script and replaced with this...
<script type="text/javascript" src="../../Scripts/Loader.js"></script>
Added script to external file:
window.onload = initAll;
function initAll() {
function Pausing() {
window.setTimeout(ShowLoader, 1);
}
function ShowLoader() {
if ((typeof Page_IsValid === 'undefined') || // asp page has no validator
(Page_IsValid != null && Page_IsValid)) {
var i = document.getElementById("loader");
var img = document.getElementById("img");
i.style.display = "block";
setTimeout("document.images['img'].src=document.images['img'].src", 10);
Endpausing();
}
}
function HideLoader() {
var i = document.getElementById("loader");
i.style.display = "none";
}
function Endpausing() {
window.setTimeout(HideLoader, 4000);
}
}
Then I receive the previously mentioned error.
Any help would be greatly appreciated!
Always use ResolveUrl to call your script files like this
Lets assume your script is in Script folder of your root path with a file Name as MyScriptFile.js
<script type="text/javascript" src="<%= ResolveUrl ("~/Scripts/MyScriptFile.js") %>"></script>
EDIT : you can use ResolveUrl or ResolveClientUrl based on your needs
ResolveUrl creates the URL relative to the root where as
ResolveClientUrl creates the URL relative to the current page.
Based on your question : How to use an external javascript file in asp.net
<script type="text/javascript" src="http://www.xyz.com/test.js"></script>

Categories