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>
Related
Apparently, scripts in HTML template only work in HTML template itself, and not the page that the HTML template is injected into. (The scripts still execute, but they rely on jQuery, and even though its imported before the others, it spits out errors.)
To elaborate, here is my code:
function cleanDocument(names) {
var element = document.documentElement;
for (var i = element.attributes.length - 1; i >= 0; i--) {
element.removeAttribute(element.attributes[i].name);
}
for (var i = 0; i < names.length; i++) {
var elements = document.getElementsByTagName(names[i]);
if (elements.length === 0)
document.documentElement.appendChild(document.createElement(names[i]));
}
window.stop();
}
var documentElements = ['html'];
cleanDocument(documentElements);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var PBSKPage = xhttp.responseText;
document.querySelector('html').innerHTML = "";
loadPBSKPage();
function loadPBSKPage() {
document.querySelector('html').innerHTML = PBSKPage;
}
}
};
var actualpage = chrome.runtime.getURL('/2015/wildkratts/wk_homepage.html')
xhttp.open("GET", actualpage, true);
xhttp.send();
function insertAndExecute() {
var scripts = Array.prototype.slice.call(document.getElementsByTagName("script"));
var jquery = document.createElement("script");
jquery.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
document.head.appendChild(jquery);
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src != "") {
var tag = document.createElement("script");
tag.src = scripts[i].src;
document.getElementsByTagName("head")[0].appendChild(tag);
}
else {
eval(scripts[i].innerHTML);
}
}
}
This code applies to https://pbskids.org/wildkratts/.
Basically, what it does is it wipes the document clean, and then, using XMLHttpRequest, it injects the HTML template inside the extension onto the page. However, all the scripts inside the HTML template require jQuery, and when accessing the overriden page (pbskids.org/wildkratts/), the scripts don't fully work due to uncaught errors (i.e. Uncaught ReferenceError: $ is not defined) that would be resolved if jQuery was imported.
I then accessed the HTML template URL itself, and what do you know, the scripts actually executed no problem.
Here's the order of my script tags in the HTML template:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/jquery_libraries/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery-1.11.0.min.js"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.nivo.slider.pack.js" type="text/javascript"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.touchSwipe.min.js" type="text/javascript"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/retina.min.js"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/plugins.js"></script>
<script type="text/javascript" src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/swfobject.js"></script>
<script type="text/javascript" src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.mobile.custom.min.js"></script>
<script type="text/javascript" src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/vendor/jquery.nivo.slider.3.2.plus.sliding.js"></script>
<script src="chrome-extension://niabfndainielhgpcjenbpodannhfofj/2015/pbsk_resources/wildkratts/js/pxaudio.min.js"></script>
<script type="text/javascript" src="https://www-tc.pbskids.org/includes/javascript/bridge.urls.js"></script>
<script type="text/javascript" src="https://www-tc.pbskids.org/includes/javascript/bridge.js"></script>
I would like to make it so that the scripts fuylly work correctly when on the overriden page itself, not the HTML template. I guess I could make it redirect to the HTML template, but I really don't want that.
When adding script elements individually via appendChild or similar DOM methods, each script with src is running asynchronously i.e. it doesn't wait for the previous script so it may run before jQuery runs. The solution is to wait for load event before running the next script:
async function insertAndExecute() {
for (const orig of document.querySelectorAll('script')) {
const copy = document.createElement('script');
copy.textContent = orig.textContent;
copy.src = orig.src;
orig.replaceWith(copy);
if (copy.src) {
await new Promise(resolve => copy.addEventListener('load', resolve, {once: true}));
}
}
}
I'm trying to get this to work:
I've got string variable in a file called test.js. Depending on some values the file is created by a php script and it says something like: var test = 'up' or: var test = 'down'.
Now, I would like display a certain image on my website depending on the value of var test. So in my html code I add this to the header:
<script type="text/javascript" src="test.js"></script>
Then in the body I write:
<script type="text/javascript">
function Test(){
if (test == 'up'){
document.getElementById("test").src = '/img/arrows/arrow_up.png';
}
else if (test == 'down'){
document.getElementById("test").src = '/img/arrows/arrow_down.png';
}
else {
document.getElementById("test").src = '/img/arrows/arrow_neutral.png';
}
}
</script>
And I add in the image with:
<img id="test" src="" class="test">
However, nothing is displayed on the page. Can someone help me out?
You have to call Test() somewhere, the code below executes it, when the page is fully loaded, so the other .js file has executed(test has been set) and the <img> is on the page.
var test = 'down';
function Test() {
if (test == 'up') {
document.getElementById("test").src = '/img/arrows/arrow_up.png';
} else if (test == 'down') {
document.getElementById("test").src = '/img/arrows/arrow_down.png';
} else {
document.getElementById("test").src = '/img/arrows/arrow_neutral.png';
}
}
window.onload = function() {
Test()
};
<img id="test" src="" class="test">
First of all, try to put manually a src to see if the src is correct :
<img id="test" src="/img/arrows/arrow_up.png" class="test">
If it works, you should call your Test() function somewhere :
window.onload = function() {
Test();
};
To make simplier, you can use JQuery (not obligatory) :
You should add jquery reference to your html page (depending on your scripts folder, the link can change) :
<script src="~/Scripts/jquery-3.2.1.js"></script>
And you can change your Test() methode on this :
function Test(){
debugger;
if (test == 'up'){
$("#test").attr("src", '/img/arrows/arrow_up.png');
}
else if (test == 'down'){
$("#test").attr("src", '/img/arrows/arrow_down.png');
}
else {
$("#test").attr("src", '/img/arrows/arrow_neutral.png');
}
}
Finally, to check if your test parameter is correct, you can put a debugger in order to debug your code in any browser.
If you open the developper tools of your browser, (by pressing on F12 on the browser) you can debug your code. The code will hit the debugger keyword.
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;
}
I'm trying to make some small changes to an existing vb.net website that was written by someone who no longer works for the company, but every time a javascript function is called from a script file other than the one it's defined in, I see "Uncaught Reference Error: undefined is not a function" in Chrome's console.
Some of the scripts are being loaded in the master file:
<script type="text/javascript" src="Scripts/jquery-1.8.3.min.js"></script>
<script type='text/javascript' src="Scripts/JSExtensions.js"></script>
<script type='text/javascript' src="Scripts/GlobalUtilityFunctions.js"></script>
<script language="javascript" type="text/javascript">
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame() {
}
</script>
And the rest are loaded in the page itself:
<script type='text/javascript' src="Scripts/GridCalcFunctions.js"></script>
<script type='text/javascript' src="Scripts/InputEventHandlers.js"></script>
<script type='text/javascript' src="Scripts/FocusHandlers.js"></script>
<script type='text/javascript' src="Scripts/ProjectPageFunctions.js"></script>
<script type="text/javascript">
$(document).ready(function () {
});
$(window).unload(function () {
SaveOnExit();
});
function setPIDNumberLabel(ctlID, strVal) {
var val = strVal;
var ctl = top.$get(ctlID);
if (ctl != null) {
ctl.innerHTML = val;
}
}
</script>
GlobalUtilitesFunctions has no trouble accessing JSExtensions on other pages, but does here even though both are loaded in the master. I thought that must mean that the problem is caused by one of the files loaded on this page, but commenting them all out doesn't fix the issue.
As a specific example, GlobalUtilitiesFunctions contains this:
function GetAttributeSelector(attName, attValue, attOperator,attNot) {
attOperator = String.deNullValue(attOperator, "=");
[more code]
}
And I get an error that String.deNullValue is undefined, but over in JSExtenstions is:
String.iifValueIsNullOrEmpty = function (val, trueVal,falseVal) {
falseVal = String.getArgValue(falseVal, val);
if (String.isNullOrEmpty(val)) {
return trueVal;
}
else {
return falseVal;
}
}
String.deNullValue = function (val,defaultVal) {
var ret = "";
defaultVal = String.iifValueIsNullOrEmpty(defaultVal,"");
ret = String.iifValueIsNullOrEmpty(val,defaultVal);
return ret;
}
I've also tried running the site on a server (instead of inside Visual Studio) without solving the problem. Does anyone have an idea what might be causing this?
Here you can see this:
"A variable declared (using var) within a JavaScript function becomes LOCAL to the function.
The variable gets a local scope: It can only be accessed from within that function."
try to define functions like
function deNullValue(val,defaultVal) {
var ret = "";
defaultVal = String.iifValueIsNullOrEmpty(defaultVal,"");
ret = String.iifValueIsNullOrEmpty(val,defaultVal);
return ret;
}
I am testing with pure JavaScript if browser seems to support HTML5 and if so, I want to load jQuery and then process the rest of page. If not, some redirection will occur.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('script')[0];
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'js/jquery.js';
s.parentNode.insertBefore(jq, s);
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
But the code above is not working properly, because I got error
Uncaught ReferenceError: $ is not defined
which is clearly saying that jQuery library has not been loaded.
Why? What is wrong with conditional script loading in my code above?
This is a case where it may make sense to use document.write(). You'd need to put this code in the <body> instead of the <head>:
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
document.write( '<script src="js/jquery.js"><\/script>' );
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
Or, you may be able to use an ordinary <script> tag to load jQuery, but put it after your conditional redirection:
<script>
var canvas = document.createElement('canvas');
if( !( canvas && canvas.getContext && canvas.getContext('2d') ) ) {
// ... redirection ...
}
</script>
<script src="js/jquery.js"></script>
<script>
$(function () {
//...
}
</script>
With either of these approaches, the order of execution is:
The first <script>.
The loading of jquery.js, whether done with document.write() or a simple <script> tag.
The final script.
When you insert a script tag like you are, it will be loaded in the background, not immediately and thus your next script will run before jQuery is loaded. You will need to attach a listener such that you know when jQuery is successfully loaded and you can then run your scripts that use jQuery.
Here's an article that describes how to know when a dynamically loaded script is loaded: http://software.intel.com/en-us/blogs/2010/05/22/dynamically-load-javascript-with-load-completion-notification.
FYI, in your specific case, you also could just have a static script tag that loads jQuery, but place your script that detects whether to redirect or not BEFORE the jQuery script tag. That would be the simplest option.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (!canvas || !canvas.getContext || !canvas.getContext('2d')) {
// redirect here or whatever
}
</script>
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
finally working like a charm, I'm relieved myself !
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
window.onload = function(){
var jqu = "$(console.log('worked'));";
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('head')[0];
var jq = document.createElement('script');
jq.setAttribute('type','text/javascript');
jq.innerHTML = jqu;
var jqLoad = document.createElement('script');
jqLoad.setAttribute('type','text/javascript');
jqLoad.setAttribute('src','jquery-1.10.0.js');
jqLoad.setAttribute('id','jqloader');
s.appendChild(jqLoad);
document.getElementById('jqloader').onload = function(){
console.log('loaded');
s.appendChild(jq);
}
}
else {
// ... redirection ...
}
console.log(document);
}
</script>
</head>
<body>
</body>
</html>
jsbin Demo
explanation :
1- using dom functions to append or insert elements are always the best (dynamic and safer more than anything else), and document.write is not recommended over that.
2- at parse-time, whatever functions you have in your script will be evaluated thus you will get an error if you have the script and not loaded the library yet.
3- loading the library and executing the relevant script in the same tag is not recommended. better do the script in another tag (after loading is done completely) to ensure it will work.
4- events for document.onload ensures that the document is loaded and the doms exist so you can append children to them. as for the document.getElementById('jqloader').onload it was just to insure that the jquery library is loaded completely and added to the document, and only then the script will be added after and evaluated.
As others have said, the reason you're getting an error is because you've loaded jQuery asynchronously and it hasn't loaded yet.
There are two ways to accomplish what you want.
You can poll for window.jQuery, or you can use an asynchronous loader callback.
Since you only load jQuery only when you detect canvas support, you won't have to worry about supporting old browsers.
var async_script_load = function (s, callback) {
var script;
script = document.createElement("script");
script.async = "async";
if (s.scriptCharset) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (head && script.parentNode) {
head.removeChild(script);
}
// Dereference the script
script = undefined;
callback(200, "success");
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore(script, head.firstChild);
};
async_loader({url:'http://tempuri.org/jquery.min.js'},function() {
//call jquery here.
});
For a polling method, it's as simple as:
var checkJq = function() {
if(window.jQuery) {
//do jQuery
} else {
setTimeout(checkJq,100);
}
}
setTimeout(checkJq,100);