I have script which I load this way:
$(funcion() {
var html = ''
html += '<script type="text/javascript" src="http://example.com/test.js"></script>'
$('#divid').html(writeCapture.sanitize(html,function(){
// if my test.js returns special content i do this:
var cap = ''
cap += '<script type="text/javascript" src="http://example.com/example.js"></script>'
$('#divid').html(writeCapture.sanitize(cap))
})
})
But I have error NOT_FOUND_ERR: DOM Exception 8. Where is my mistake?
Don't load scripts like that. Use the $.getScript() function instead:
$(function() {
$.getScript('http://example.com/test.js', function() {
// the script is loaded here => you can use it
});
});
Related
I'm trying to insert an external html file into a panel/div. I'm using jquery and jeasyui to do this.
I used the onload function to create a panel and load external html file via jquery, as shown below:
<script type="text/javascript">
$(function(){
$('#tt').tabs({
onLoad:function(panel){
var plugin = panel.panel('options').title;
panel.find('textarea[name="code-'+plugin+'"]').each(function(){
var data = $(this).val();
data = data.replace(/(\r\n|\r|\n)/g, '\n');
if (data.indexOf('\t') == 0){
data = data.replace(/^\t/, '');
data = data.replace(/\n\t/g, '\n');
}
data = data.replace(/\t/g, ' ');
var pre = $('<pre name="code" class="prettyprint linenums"></pre>').insertAfter(this);
pre.text(data);
$(this).remove();
});
prettyPrint();
}
});
});
function open1(plugin){
if ($('#tt').tabs('exists',plugin)){
$('#tt').tabs('select', plugin);
} else {
$('#tt').tabs('add',{
title:plugin,
href:plugin+'.html',
closable:true,
extractor:function(data){
data = $.fn.panel.defaults.extractor(data);
var tmp = $('<div></div>').html(data);
data = tmp.find('#content').html();
tmp.remove();
return data;
}
});
}
}
</script>
<script type="text/javascript" src="prettify.js"></script>
<script type="text/javascript" src="jquery-1.8.10.js"></script>
<script type="text/javascript" src="jquery.easyui.min.js"></script>
While working on IE10, I have found that the JavaScript functions which are registered or called from the code behind are throwing exception:
"JavaScript runtime error: 'function name' is undefined".
For ex:
Code behind in the (!IsPostBack) block:
Page.RegisterStartupScript("showGCAlert", "<script language=\"javascript\">ShowGCAlert();</script>");
PageView:
function ShowGCAlert()
{
alert('GCAlert');
if(document.getElementById('hdnGCAlert').value != "1")
{
document.getElementById('divGCAlert').style.display = "Block";
document.getElementById('chkReminder').focus();
document.getElementById('btnLogin').disabled = true;
document.getElementById('Button2').disabled = true;
}
else
{
document.getElementById('divGCAlert').style.display = "none";
document.getElementById('btnLogin').disabled = false;
document.getElementById('Button2').disabled = false;
if (document.getElementById("txtUsername").value != "")
document.getElementById("txtPassword").focus();
else
document.getElementById("txtUsername").focus();
}
}
When the page loads its throws the exception even though the ShowGCAlert() exists on the dynamic page.
After continuing the exception design page shows:
<script language="javascript" src="/ABC/DEF/Scripts/Common.js"></script>
<script language="javascript">
document.body.style.overflowY="hidden";
document.body.style.overflowX="hidden";
var jsAppName ='ABC';
</script>
<script language="javascript">
function window.onresize()
{
document.cookie = "resX="
+ document.body.clientWidth
+ ";resY="
+ document.body.clientHeight
+ ";path=/";
}
window.onresize();
</script>
<script type="javascript">
ShowGCAlert();
</script>
<script language="javascript">
document.getElementById('txtPassword').focus();
</script>
In ie9 or IE10 compatibility view its working fine. Please show me where i am doing wrong.
Try placing the script at the end of the page using RegisterClientScriptBlock and call it.
Page.ClientScript.RegisterClientScriptBlock("showGCAlert",
"<script type=\"text/javascript\">ShowGCAlert();</script>");
I'm using a plugin that I found from searching the web called Apprise. It has worked well for what I have needed thus far. But, I want to apprise the facebook login plugin and to to that I need to following code:
<fb:login-button scope='email,publish_stream'>
Login
</fb:login-button>
<script type='text/javascript' src='http://connect.facebook.net/en_US/all.js'></script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '123456789',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location = '/fb_redirect.php';
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
Anything that you want to be apprised can be done by putting
apprise();
in the javascript. However, putting the <script></script> tags inside of the JS code (apprise();) causes all sorts of confusion because it's not clear where the JS code ends.
Any ideas?
The method that works in both <script> blocks and inline Javascript is \uxxxx, where xxxx is the hexadecimal character code.
< - \u003c
> - \u003e
" - \u0022
' - \u0027
\ - \u005c
& - \u0026
Demo:
HTML:
<div onClick="alert('Hello \u0022>')">click me</div>
<script>
var s = 'Hello \u003c/script\u003e';
</script>
You need to break up the close script tag, if I'm reading your question right:
var test = '...... </scr'+'ipt>......';
Script tag in JavaScript string
Try breaking up the tags:
apprise('<scri' + 'pt>alert("hello");</sc' + 'ript>');
You need just to escape the / character:
BAD, exception
<script>
var html = "<script></script>";
</script>
GOOD
<script>
var html = "<script><\/script>";
</script>
To begin my page i do a check with facebook to get the login status of the user. I then create a namespace within the window object for use in other javascript files. Before I load any other javascript i need this namespace to be created, or else it will be undefined when i try to access it. Sometimes it completes first, and sometimes it does not. How can i make sure that it happens correctly every time?
.
.
.
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
})
};
(function(d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document))
</script>
<!-- Load the script "js/main.js" as our entry point for require -->
<script data-main="js/main" src="lib/Require/require.js"></script>
specifically, i need the:
<script data-main="js/main" src="lib/Require/require.js"></script>
to not happen until the facebook function is complete
Move the code relying on the namespace into the Facebook callback. If it's the <script data-main="js/main" src="lib/Require/require.js"></script>, create the script element dynamically:
// ...
FB.getLoginStatus(function(response) {
// store data on the user inside of a namespace
// inside of the window object so it can be accessed
// from anywhere. Use this like '$_SESSION'
console.log('doing it');
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
// Create the script element when ready
var script = document.createElement('script');
script.setAttribute("data-main", "js/main");
script.src = "lib/Require/require.js";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
// Or instead of `document.getElementsByTagName('script')[0].parentNode`
// you can use `document.documentElement` or `document.getElementsByTagName('head')[0]
// or a few others
})
};
You could move it all to one place as TJ suggests. Or you could check to see if your variable is created before attempting to run your own code:
// First this:
FB.getLoginStatus(function(response) {
window.easyUserData = {
fbRespose: response,
site: <?php echo '"'.$site.'"'; ?>
};
});
// Later in the code:
(function () {
var isFBLoaded = function () {
// If FB has loaded - run our code
if (window.easyUserData) {
myOtherFBStuff();
}
// If not - check again in 500 ms
else {
setTimeout(isFBLoaded, 500);
}
};
var myOtherFBStuff = function () {
// do stuff here
};
isFBLoaded();
})();
For jQuery template:
http://api.jquery.com/category/plugins/templates/
I want to be able to dynamically load the templates from a server, rather than predefining it on the page.
The demos I saw on the projects are using predefined templates. After some research I found out that it is possible.
I try doing this and it doesn't work:
<script src="child.html" type="text/x-jquery-tmpl"></script>
I tried doing this and it doesn't work:
$(function () {
$.get("child.html", function (data) {
//Add template
$.template("tmplChild", data);
});
//template binds before async call is done
$.tmpl("tmplChild").appendTo("body");
});
And finally, I have get it down to the following hack:
so.html (This is the main page):
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
<script type="text/javascript" src="so.js"></script>
<script type="text/javascript">
$(function () {
initTemplates(templateReady);
});
function templateReady() {
$.tmpl("tmplChild").appendTo("body");
}
</script>
</body>
</html>
child.html (This is the child template)
<h1>Child Loaded</h1>
so.js (This is my hack for ajaxly loading the js templates)
function initTemplates(callback) {
var templateUrl = "child.html";
var templateName = "tmplChild";
initTemplate(templateUrl, templateName, callback);
}
function initTemplate(url, name, callback) {
var opts =
{
type: "GET",
url: url,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
xmlCallback(data, name, callback);
},
error: function (x) {
xmlCallback(x.responseText, name, callback);
}
}
$.ajax(opts);
}
function xmlCallback(data, name, callback) {
if (typeof data != "string") {
if (window.ActiveXObject) {
var str = data.xml;
data = str;
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(data);
data = str;
}
}
//only takes strings!
$.template(name, data);
callback();
}
And here's what I don't like about it.
This doesn't work on Chrome
It seems like a lot of code just to load some template
I lost the ability to use $(document).ready(). I must now put all my code in this templateReady() method to be "template safe".
Is there a way around this?
Thanks,
Chi
Just load the template body as simple text and forget about putting it in a dummy <script> block. You can use $.tmpl(body, params) to populate the template and turn it into a string for appending to the DOM.
The whole thing with "not really script" <script> blocks is just a convenience useful in some situations.
edit — example:
$.get("/some/url/for/a/template", function(templateBody) {
var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});
If the goal is to fetch a unique template each time you get data via ajax, then you might try fetching the template at the same time and include it in your data, that is if you have the luxury of modifying the returned object (anonymous object in .Net). Then you can store the template anywhere you want and you only need 1 ajax call for both the data and the template.
Refer here:
https://www.npmjs.com/package/jlate
use CDN:
<script src="https://cdn.jsdelivr.net/combine/npm/lodash,npm/jlate#0.0.2/jlate/JLate.min.js"></script>
HTML Code:
<body>
<div>
<jlate id="my_temp" src="template/jlate_title.html" type="template">
Loading...
</jlate>
</div>
</body>
Javascript:
$$("#my_temp").jlate({ title: "sample title"});