how to load external javascript inside partial view dynamically? - javascript

I'm using jquery's .html() function to inject a html file into a partial div of the main page of my application. In the injected partial html page, there is a javascript reference such as script(src='../../javascripts/partialFunctions.js').
The jquery function and the main page are like:
$('.partialDiv').html(htmlResult);
<div>main page</div>
<div class='partialDiv'></div>
<input type='button'>button</input>
When the user click a specific button on the main application page, the jquery function will got called and the html file will got injected to the main page.
The problem is every time a new htm file got injected, the browser will load the script file. So there will be many duplicated javascript functions after the user clicked the button several times.
How can I do this dynamically and avoid the duplication of javascript functions?
Thanks in advance!

You can remove the script tags and references from the htmlResult page.
Then use $.getScript('myscript.js') to import the necessary JavaScript files.
More info on getScript() here
So to load in the script and make sure it only loads in once:
var window.foo = false; //Outside the document.ready
$('.partialDiv').html(htmlResult);
if(window.foo == false){
$.getScript("js/myScript.js", function(data, textStatus, jqxhr){
console.log('Script loaded');
window.foo = true;
});
}

I just did a quick test, it looks like script tags are stripped out anyways when you call .html(). So you should be able to simply do:
var html = "<html><script></script></html>",
cleanedHtml = $(html).html();
myEl.html(cleanedHtml);

Related

javascript onclick null in custom js file

I'm trying to simply detect clicking an A link to display an Alert box. Whenever I place the script inside the php file my a link is located, it works fine, but whenever I place it in my custom JS file, it doesn't detect it, and I get the error 'Uncaught TypeError : Cannot set property "onclick" of null'.
The link between the php page and custom js page is definitely working, as I have previous working code on the page. It simply wont detect my A link it its located in an external script.
HTML
<a id="ConfirmHolidayClose" href="#">
<img src="assets/img/close-button.png" alt="Holiday-request-close-button"
class="CloseButton" />
</a>
JAVASCRIPT
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
UPDATE - Forgot to mention sorry, my a link is nested inside div called 'ConfirmHoliday'.
I have JS code manipulating the ConfirmHoliday div inside my Custom JS, so it cant be loading after because it is finding its parent div perfectly well at the moment.
The javascript file runs before the element is created, thus it doesn't exist. To solve this, you have couple options:
1) Surround the code with a window.onload function
window.onload = function () {
// Your code here
};
2) Put it in a separate js file and add a defer property to the script tag.
<script src="yourScript.js" defer="defer"></script>
3) Put the script tag after the anchor tag
It's trying to access the ConfirmHolidayClose element before it exists maybe? Where is your JS loaded in your page? I'm guessing in your <head>
A few solutions:
1) Move your script to bottom of page just above </body>
2) wrap your JS in dom ready function, this ensures no JS will run until the DOM tree exists. Easiest with jQuery, example below...
jQuery example
$(function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});
Vanilla example
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("ConfirmHolidayClose").onclick=function(){
alert("Working");
}
});

jquery function include only once?

I'm building single page application with jquery. so assume I have a sidebar like this
dashboard.html
order.html
and each time i click on it I load the content via ajax. It work fine but I go back and forth btw pages I notice the script got loaded twice or more. How to solve this?
Put the scripts and HTML in separate files. Then keep track of whether you've already loaded a script, and don't load it again.
var dashboard_js_loaded = false;
$("#dashboard").click(function() {
$("#content").load("dashboard.html", function() {
if (!dashboard_js_loaded) {
$.getScript("dashboard.js", function() {
dashboard_js_loaded = true;
});
}
});
});
Maybe a library like require.js can be used to manage this more generally. Or you can just write a simple function that keeps track of which JS files have been loaded in an object.

javascript not loaded from django template when URL is invoked from jQuery load()

I have a django generated page, and in it I have a jQuery on click handler that loads another django page using the jQuery load() function:
$("#loadit").on("click", function() {
load_it($("#loadit"), url);
});
function load_it(el, url)
{
var el_wf = $('<div />');
el_wf.load(url, function (html, status) {
el.children().remove();
el_wf.show();
el_wf.appendTo(el);
});
}
In that second django template I have some code like this:
<script type="text/javascript" src="/static/scripts/myscript.js"></script>
.
.
.
<div>
<script>
function_in_myscript();
</script>
</div>
When I click on the element in the first page, and the second page is loaded that js function is not invoked. There are no errors, and the rest of the template is run and the page is generated.
But if I go to the second URL directly from my browser the js function is run.
Is there something with load() that is preventing this from working?
JavaScript inserted as DOM text will not execute. The W3C Specification for XMLHttpRequest states: Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.
The solution is to call JavaScript’s eval() function on the text of the script. Using jQuery it is very easy to iterate through the collection of script tags and to eval() contents of the TextNode. However this looks like a bad practice.
Using script tag in second html is not a good way of loading a new js file. I suggest that you use RequireJS for this purpose. RequireJS takes a different approach to script loading than traditional tags. It can run fast and optimize well.
Here is an example to demonstrate the usage, In first File:
<script type="text/javascript" src="/static/scripts/require.js"></script>
.
.
.
<script type="text/javascript">
require.config({
paths: {
myscript: '/static/scripts/myscript'
}
});
$("#loadit").on("click", function() {
load_it($("#loadit"), url);
});
function load_it(el, url)
{
var el_wf = $('<div />');
el_wf.load(url, function (html, status) {
el.children().remove();
el_wf.show();
el_wf.appendTo(el);
require(['myscript'], function(myscript) {
function_in_myscript();
});
});
}
</script>
In that second django template just load the html code. No need for loading script.

load widgets after loading conten

What am doing is writing wizards using existing forms and list views. we want to combine these forms in single page. here is a script we have used to get form from url then called function to bind widgets. first line is loading content of form but bindWidgets is not working. While bindWidgets is working on preloaded content which is default loaded with page.
<script>
$(document).ready(function() {
$("#template_form").load("/push_templates/pushtemplate/create/ #zform");
bindWidgets();
});
</script>
Do we need to wait for load, as it seems that 2nd line is executed prior to content loaded. How can we go to wait stat or better way to call bind function after load complete.
Use this;
<script>
$(document).ready(function() {
$("#template_form").load("/push_templates/pushtemplate/create/ #zform", function() {
bindWidgets();
});
});
</script>
You can see demo here: jsfiddle

How to execute Javascript from external HTML

If I have a button that executes the code
$('#main').load('welcome.html');
and in welcome.html I have a button that executes the code
$('#main').load('otherpage.html');
the Javascript isn't executed, regardless of whether that function is on the parent file's HTML code or the child's.
How can I get a Javascript function to work from externally loaded HTML files?
EDIT
Here's a bit more of a sample...
Homepage:
<body>
<div id="main"></div>
</body>
<script>
document.onLoad(){
$('#main').load('welcome.html');
}
function show(file){
$('#main').load(file+'.html');
}
</script>
welcome.html page:
Test
...however when the Test button is clicked, test.html is not loaded into the Main div.
EDIT 2
Here is what the current state is and what the issue is - exactly.
I've uploaded the bones of the code to PasteBin.
When the 'grid' button is clicked, the content changes and the footer changes.
However, the footer, which has URLs based on Javascript, comes up with the error:
Uncaught SyntaxError: Unexpected token ILLEGAL
...when trying to access the 1i.html page.
There's a difference between test the variable and 'test' the string:
Test
Probably should be:
Test
It is important to understand that when loading script into page via AJAX that the main page has already gone through document.ready . Thus, any code you load will fire immediately.
If the code you load precedes the html it references, it will not find that html when it fires.
Placing the code after the html in remote page will resolve this issue
Check jQuery.live() and jQuery.on().
Maybe your eventhandler is wrong. When you import new markup via load() or ajax(), you have to initialize the handlers from new document. The easiest way is using jQuery.on or jQuery.live() instead of jQuery.click().
$('MYBUTTON').live('click', function(){
$('#main').load('your_url.html')
})
or use the callbackfunction to (re-)initialize the buttons event.
A better solution is this: Just add the target_url to buttons rel attribute...
<button rel="YOUR_URL.html">Open Page</button>
$('button[rel]').live('click', function(){
$('#main').load($(this).attr('rel'));
})

Categories