How to dynamically change my includes to js files? - javascript

I have a hidden div which contains my new links:
<div id="links" style="display:none">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
...
</div>
The links I want to change are in my head:
<head id="myHead">
<!-- My olds links I want to replace -->
</head>
I've tried something like this:
updateLinks();
function updateLinks() {
var str = document.getElementById("links").innerHTML;
document.getElementById("myHead").innerHTML = str;
}
But my head don't receive the new links.
I want to update my links because I download html files and when I try to open them I have ERR_FILE_NOT_FOUND
Can you help me please?

What do you want is a asyncrounous module loader (AMD) like requirejs.
You can load all you files on demand. Using it it's simple to implement a lazy script loader. :)

Would simply loading the new js scripts suffice for your purposes?
You could use the jQuery method getScript to call it for each attribute src of your scripts in your div, like:
$("#links script").each(function() {
var src = $(this).attr("src");
$.getScript( src, function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
});

Here is your code
$(function() {
updateLinks();
});
function updateLinks() {
var po = document.querySelector('#links script');
var s = document.querySelector('head');
s.appendChild(po, s)
}
The jsFiddle: http://jsfiddle.net/BenoitNgo/6vca82wh/11/
The question has been answered already on this forum.

Related

jQuery: On load event not working consistently

I'm trying to lazy-load images using the following script (lazy-load.js):
function lazyLoadImage(imgContainers) {
var img = $('<img src="">');
imgContainers.each(function (i, elm) {
img.attr('src', $(elm).data("large"));
img.on('load', function () {
$(this).addClass('loaded');
});
img.addClass('picture');
$(elm).append(img.clone(true));
});
}
$(window).on('load',function () {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
});
The problem is, everything goes well if I load the script using <script></script> tag but when the script is loaded dynamically using jquery $.getscript() the script is not working consistently (i.e. sometimes the onload event is not triggering).
Loading script dynamically:
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
});
So, why the script is not working consistently??
window.load fires when the window finished loading. It doesn't fire a second time when you load more content via ajax because there is no way to tell for the browser when you will be finished loading additional content. So for all stuff you do via ajax you have to execute all functionality again.
In your case I guess you want these things to happen:
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
So I would say put this in a function and just call it when you finish loading the script:
function lazyloadimages() {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
}
$(window).on('load',function () {
lazyloadimages(); // notice this change, put the stuff in an extra function so you can reuse it!
});
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
lazyloadimages();
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
// oh no something went wrong, no need to lazyload something here!
});

How can I fire a function in a click(function)?

I have a javascript file which I want to start when a div has been clicked.
I have already this when clicking the div "option_one", an input will be set to "Option 1":
$("#option_one").click(function() {
$("#input").val('Option 1');
});
How can I fire another js file after clicking the div?
I try something with getScript but I couldn't get it working.
Kind regards,
Arie
There is no need to load the calculate.js file on the click event. Just load it with the page load like so:
HTML:
<!--Your page HTML here... -->
<!--Before your closing body tag-->
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript" src="calculate.js"></script>
JS:
// This is inside somefile.js
$("#option_one").click(function() {
$("#input").val('Option 1');
// This function is inside calculate.js
calculate();
});
$("#option_one").click(function() {
$("#input").val('Option 1');
$.getScript( "path/calculating.js" )
.done(function( script, textStatus ) {
//Just after the scripts finishes loading you will be able
//to perform/use functionality included on this script
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
console.log("Triggered ajaxError handler.");
});
});

How to use jquery in a external .js file?

In my website, there include such 2 files: index.php, script.js
Of course, it is much more complicated in the web site and the above only shows a part of it.
In index.php, there is a div element
<div id="phb29" class="drag ph hour01">Testing</div>
In script.js,which is a pure javascipt file,below show a part that i want to use a jquery function .switchClass() (from http://api.jqueryui.com/switchClass/) to switch the class of div element.
//... other normal js codes
switchClassHour = function(){
$(function (){
$( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
return false;
});
}
//other normal js codes...
I only want to call that jquery when I call the switchClassHour() function but not the web page is loaded(i.e. $(document).ready(function (){...}); )
I have included the source in the in index.php:
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="script.js"></script>
But finally, the chrome browser gives me this error occurring at the line $(function (){ when I trigger switchClassHour():
Uncaught TypeError: boolean is not a function
What should I do, thank you !!!!! :):)
The variable toHour does not appear to be defined within the function switchClassHour.
Try this
switchClassHour = function(){
/* `toHour` ? */
if (window.jQuery) {
/* $(function (){ */
$( "#phb29" ).switchClass( "hour01", "hour03", 1000 );
/* `return false;` ? */
/* }); */
};
};
switchClassHour(); /* just noticed, is the function actually called ? */
Edit
Try this
switchClassHour = function(){
/* `toHour` ? */
if (window.jQuery) {
/* $(function (){ */
console.log($.now())
/* `return false;` ? */
/* }); */
};
};
switchClassHour();
Is $.now() return'ed at console?
Is $ utilized in other parts of non-jquery pieces?
See also https://api.jquery.com/jQuery.noConflict/
Edit
Try this
switchClassHour = function() {
jQuery.noConflict();
(function( $ ) {
console.log($.now(), jQuery.now())
})(jQuery);
};switchClassHour();
Hope this helps
function switchClassHour(){
if(document.getElementById('jq')){
//original switchClassHour() code.
}
else{
var jq = document.createElement('script');
jq.src = "WHATEVER SOURCE YOU WANT TO LOAD FROM (PROBABLY GOOGLE)";
jq.id = "jq";
document.getElementsByTagName('head').item(0).appendNode(jq);
//Original switchClassHour() code
}
}
I don't know if this is guaranteed to work since I don't know if you'll be able to load jQuery fast enough to call your function immediately afterwards. If this doesn't work because jQuery isn't loading fast enough then the only outcome I could see is adding a delay but that's ugly. To be honest if you're using jQuery I would just load it from Google normally in the <head> of your page. Most people have it cached already.

$.html renders script as content

For a project i'm dynamically loading content that consist of html and javascript. Until now i was using jquery 1.8.3 but while cleaning up i wanted to update to 1.10.1.
I've narrowed my problem down to the way i use the $.html() function on my content div.
In jquery 1.8.3:
var content = $("#content");
contentDiv.html("<script> alert('Testing'); </script>")
shows a alertbox with the content 'Testing', while in newer jquery versions the same code the string is inserted into the DOM and then the alertbox also appears. I'd wish to not have the tags shown.
context javascript:
this.loadPage = function(page, callback){
$.get(page.ViewFile, function(view){
var content = $("#content");
$("#content").html(view);
}};
The page getting loaded contains, which is stored in the variable view as a string.
<h1>New Content</h1>
<div id="newContent"></div>
<script>
function View(){
this.InitializeView = function(model){
//code
}
this.UpdateView = function (model){
//code
}
}
</script>
Seems that the browser detect the </script> (the end of script tag) that is inside of string as a real closing when we put our code in the head of page.
This is the reason why the error is thrown in the webpage (EXAMPLE):
Uncaught SyntaxError: Unexpected token ILLEGAL fiddle.jshell.net/:22
I guess that you have to move your javascript code into a separate file like main.js, for example.
Tested it locally and it works:
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="main.js"></script>
<script type="text/javascript">
setTimeout(function () {
$("body").text("Testing now from HTML: using <script>");
setTimeout(function () {
$("body").html("<script>alert('This alert will fail.')</script>");
}, 1000);
}, 2000);
</script>
</head>
<body></body>
</html>
Javascript (main.js)
$(document).ready(function () {
$("body").html("<h1>Wait one second.</h1>");
setTimeout(function () {
$("body").html("<script>alert('Tested')</script>");
}, 1000);
});
Even the text editors detect it as closing tag:
Solution
1. Create scripts from jQuery
var content = $("#content");
var script = $("<script>");
script.html("alert('Testing');");
content.append(script)
1. Use &
Basically you have to replace < with &lt, > with &gt and & with &amp, as described in this answer:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
For more information see this question.

Uncaught syntax error with jquery plugin and chrome, works fine in other browsers

Basically I'm trying to develop a simple plugin that allows us to dynamically generate our GA onclicks straight from JSON. So I developled this quick script. Works great but chrome fires "Uncaught SyntaxError: Unexpected identifier"
Suggestions?
Test HTML file:
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="modules/onclicks/onclickify.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON('modules/onclicks/clicks.json', function(data) {
$('#analytics').onclickify(data);
});
});
</script>
<script id="analytics"></script>
jQuery plugin file
(function( $ ){
$.fn.onclickify = function(clicks) {
var onclicks = "";
return this.each(function() {
$.each(clicks, function(key, value){
onclicks += "$('"+value.selector+"')";
onclicks += ".live('click', function(){\n";
onclicks += "_gaq.push(['_trackEvent',";
onclicks += value.name+"','";
onclicks += value.label+"','";
onclicks += value.action+"');\n";
onclicks += "});\n\n";
});
$(this).append(onclicks);
});
};
})( jQuery );
That's not going to work. You can't append a blob of jQuery source code like that. Well, you can, but it's not going to do anything like what you think it is.
I'm not sure what exactly you're trying to do, but I think you could just do it like this:
(function( $ ){
$.fn.onclickify = function(clicks) {
return this.each(function() {
$.each(clicks, function(key, value){
$(value.selector)
.live('click', function(){
_gaq.push(['_trackEvent',
value.name,
value.label,
value.action
]);
});
});
});
};
})( jQuery );

Categories

Resources